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, could do it iteratively?
Confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
The sequence traversal order of binary tree is left-root-right, which can be solved by both recursive and non-recursive methods. We first look at the recursive method, very direct, to the left Dial hand node call recursive function, the root node access value, the right child node and then call the recursive function, the code is as follows:
//recursionclassSolution { Public: Vector<int> Inordertraversal (TreeNode *root) {Vector<int>Res; Inorder (Root, res); returnRes; } voidInorder (TreeNode *root, vector<int> &Res) { if(!root)return; if(root->left) inorder (root->Left , RES); Res.push_back (Root-val); if(root->right) inorder (root->Right , res); }};
Next we look at the non-recursive solution, but also the problem requires the use of the solution, need to do with the stack, the idea is to start from the root node, the root node is pressed into the stack, and then all of its left dial hand nodes are pressed into the stack, and then the top node of the stack, save the node value, and then move the current pointer The next cycle, all of its left dial hand nodes can be pressed into the stack. This ensures that the access order is left-root-right and the code is as follows:
//non-recursionclassSolution { Public: Vector<int> Inordertraversal (TreeNode *root) {Vector<int>Res; Stack<TreeNode*>s; TreeNode*p =Root; while(P | |!S.empty ()) { while(P) {S.push (P); P= p->Left ; } P=S.top (); S.pop (); Res.push_back (P-val); P= p->Right ; } returnRes; }};
[Leetcode] Middle sequence traversal of binary tree inorder traversal two