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:
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):
in this case if
does not hold, perform 83 line return
statement, then de-stacked, back to the line 78, at this time root指向2(因为此时程序已经来到了新的栈顶),并且向这个新栈顶返回了一个空的seq
:
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 ( root
point 4), to thereby carry out line 78, root
point 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 root
path of the node junction on):
Similarly, the implementation of return
the statement, de-stacked, the seq
(back only 2) to return to this layer, this layer root
point 4, 4 is then deposited seq
;
to line 80, to call inOrder()
such that root
right child point 4, the right child is empty, it is returned and unstack, root
redirected 4, the line 80 at this time is finished, the entire if
finished, return seq
and exit the stack, root
returns to 2, 2-rooted subtree in preorder completed, the system stack:
continue , The return line 78, root
point 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.