0
$\begingroup$

When I study Binary Search Tree, I try to use a pencil and paper to scratch the process of in-order traversal. However, I find that it is hard to maintain the call stack in my brain without paper and notes when the height BST is high.

Question: What should I? Is it normal and should I practice more?

$\endgroup$

2 Answers 2

2
$\begingroup$

Do not consider call stacks for recursive algorithms. Ever. Forbidden!

Learn to understand recursive algorithms like any other algorithm that calls other procedures: Assume the calls do their work correctly, and concentrate on making sure the right calls are made, and the results are combined correctly.

Separately, try to find some criterion by which the recursive calls are to "smaller" instances of the problem (assuming instance sizes are e.g. positive integers), and that all "small enough" instances are solved correctly by "base cases" (without recursive calls).

Often the recursive algorithm is modelled on some recursive definition of the structure at hand, then the mapping is simple to prove correct. For an entertaining example of a recursive program that doesn't clearly fall into this category, read and understand Rob Pike's regexp matcher (exegesis by Brian Kernighan)

$\endgroup$
1
$\begingroup$

When you are traversing a search tree, the most recently visited node uniquely determines which node will be visited next. (Visited here means actually outputted by the traversal—a node can be at the top of the stack multiple times during a traversal but is only visited during a traversal once.) So there is no reason to try to keep the entire stack in your head when working something out on paper. You can figure out what the stack has to be at any point just by looking at which node you most recently visited.

Exercise: Try looking at a binary tree and just reading off the nodes in the order they will be visited by an in-order traversal without keeping track of the stack manually.

$\endgroup$
1
  • $\begingroup$ I have gone through the process. Please show the answer. Maybe I can check my reasoning process. $\endgroup$
    – skytree
    Commented Jul 11, 2020 at 21:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.