1. Topics
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?
2. Solution 1
Class Solution {public : vector<int> inordertraversal (TreeNode *root) { vector<int> path; Stack<treenode *> St; if (root = NULL) return path; TreeNode *p = root; while (P! = NULL | |!st.empty ()) { while (P! = null) { st.push (p); p = p->left; } if (!st.empty ()) { p = st.top (); St.pop (); Path.push_back (p->val); p = p->right; } } return path; } ;
idea: The middle sequence traversal is the first access to the left node, then access, and then access to the right. Using a stack to assist, we put the left node of a node all in the stack, and then pop the leftmost node. Then the current variable pointer to its right node, also the right section of all the left node into the stack, and then popped out. Of course, the non-recursive way is still a bit difficult.
3. Solution 2
Class Solution {public : vector<int> result; void Inorder (TreeNode *root) { if (root = NULL) return; Inorder (root->left); Result.push_back (root->val); Inorder (root->right); } Vector<int> inordertraversal (TreeNode *root) { result.clear (); Inorder (root); return result; }
idea: Recursive version is still very simple.
http://www.waitingfy.com/archives/1622
Leetcode Binary Tree inorder traversal