[LeetCode] Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes 'values.
For example:
Given binary tree {1, #, 2, 3 },
1
\
2
/
3
Return [1, 3, 2].
Note: Recursive solution is trivial, cocould you do it iteratively?
This question is to traverse Binary Trees in a non-recursive way.
The following figure shows the State of the recursive workstation during the execution of the recursive algorithm:
1. When the pointer in the top record of the stack is not empty, the left subtree should be traversed, that is, the pointer pointing to the left subtree should go into the stack.
2. if the pointer in the top record of the stack is null, it should be removed to the first layer. If it is returned from the left subtree, access the root node indicated by the pointer in the top record of the current stack.
3. If it is returned from the right subtree, it indicates that the traversal of the current layer is over and the stack should continue to be rolled back.
When traversing the right subtree, you do not need to save the root pointer of the current layer. You can directly modify the pointer in the top record of the stack.
The following code is pasted in two forms:
Vector
InorderTraverse (TreeNode * root) {vector
Ans; stack
S; s. push (root); TreeNode * p = s. top (); while (! S. empty () {while (p) {s. push (p-> left); p = p-> left;} s. pop (); // empty pointer stack rollback if (! S. empty () {p = s. top (); ans. push_back (p-> val); s. pop (); s. push (p-> right); p = p-> right ;}} return ans ;}
vector
inorderTraverse(TreeNode* root){ vector
ans; if (root == NULL) return ans; stack
s; while (root|| !s.empty()){ if(root){ s.push(root); root=root->left; }else{ root=s.top(); ans.push_back(root->val); s.pop(); root=root->right; } } return ans; }