System stack binary tree recursive call

Recursion in computer science in a very important concept for Fibonacci kind of relatively simple recursive analysis is easier, but due to the binary tree involves pointer manipulation, so imitating the case traversal of the system stack.
Binary tree traversal sequence example to demonstrate:

//二叉树定义
struct TreeNode {
    TreeNode* left;
    TreeNode* right;
    int val;
    TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};

Recursive traversal sequence of:
Here Insert Picture Description
assuming binary tree as shown:

wherein the sequence preorder \ (2413 \) , can step in the method of tracking by VS corresponding variables:
when root==NULL(root指向2的左孩子), the system stack at that time (the 1 and 2 are pushed onto the stack, because preorder need to access the left child):
Here Insert Picture Description
in this case ifdoes not hold, perform 83 line returnstatement, then de-stacked, back to the line 78, at this time root指向2(因为此时程序已经来到了新的栈顶),并且向这个新栈顶返回了一个空的seq:
Here Insert Picture Description
then perform 79 lines (since this is on a function return, it will not execute again the line 78), into the 2 seq; and
perform line 80 ( rootpoint 4), to thereby carry out line 78, rootpoint 4 of the left child, the system stack at this time (see it is apparent from the bottom of the stack to stack sequentially store the root to the current rootpath of the node junction on):
Here Insert Picture Description
Similarly, the implementation of returnthe statement, de-stacked, the seq(back only 2) to return to this layer, this layer rootpoint 4, 4 is then deposited seq;
to line 80, to call inOrder()such that rootright child point 4, the right child is empty, it is returned and unstack, rootredirected 4, the line 80 at this time is finished, the entire iffinished, return seqand exit the stack, rootreturns to 2, 2-rooted subtree in preorder completed, the system stack:
Here Insert Picture Description
continue , The return line 78, rootpoint 1, into the SEQ 1, and so on, can be obtained traverse the entire sequence.

The key is: The reason for recursive calls inOrder, because now do not want to access the current node (for the sequence, first find the leftmost node), so by recursively do not want to access the current junction point pressure after the system stack, find nodes want to access, and access it using the unstack operation returns the parent node.

Guess you like

Origin www.cnblogs.com/EIMadrigal/p/11520701.html