简体   繁体   中英

please help me understanding this recursion in binary tree preorder traversal

Here when you look at position C in my given tree my recursion need to move in right side as it does not hit the base case which is return if NULL but it turn left without hitting the base case that thing just blowing my mind. The output is ABDHECFG while I think it needs to be ABDHECGF.

Please help me if you can. Thank you have a nice day.

1

Let's assume your tree looks like this:

                             A
                            / \
                           B    C
                          / \  / \
                          D E  F  G    
                           \
                            H

The order in which PreOrder traversal will work is:

Root
Left Subtree
Right Subtree

Initially you will get root as input in other words traversal will start from root node.

Steps to do pre-order:

  • take the current root and put it on stack.
  • peek the item from stack, explore it, put right and left subtrees in stack back.
  • follow prev two steps unless until we stack becomes empty.

Initially stack stck is empty;

1. put root `A` on stack
2. pop the top item from stack; explore it-> o/p: A
3. put the right and left subtrees of current node in stack back: B C
4. pop the top item from stack; explore it-> o/p: A->B
5. put the right and left subtrees of current node in stack back: D E C
6. pop the top item from stack; explore it-> o/p: A->B->D
7. put the right and left subtrees of current node in stack back: H E C
8. pop the top item from stack: explore it-> o/p: A->B->D->H
9. put the right and left subtrees of current node in stack back: E C
8. pop the top item from stack: explore it-> o/p: A->B->D->H->E
10. put the right and left subtrees of current node in stack back: C
11. pop the top item from stack: explore it-> o/p: A->B->D->H->E->C
12. put the right and left subtrees of current node in stack back: F G
13. pop the top item from stack: explore it-> o/p: A->B->D->H->E->C->F
14. put the right and left subtrees of current node in stack back: G
15. pop the top item from stack: explore it-> o/p: A->B->D->H->E->C->F->G
16. stack is empty-> EXIT! 

Pseudo-code:

function(root):
   if (root):
       print: root->value;
       function(root->left);
       function(root->right);

Note: in pseudo-code we putted left subtree first since we are doing it recursively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM