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?
Note that In-order is the root traversal
1. If you use recursion on the left root right
1 classSolution {2 Public:3vector<int> Inordertraversal (treenode*root) {4vector<int>v;5 if(Root = =NULL)6 returnv;7 if(Root->left = = NULL && root->right = =NULL)8 {9V.push_back (root->val);Ten returnv; One } Avector<int> left = inordertraversal (root->Left ); -vector<int> right = Inordertraversal (root->Right ); - the V.insert (V.end (), Left.begin (), Left.end ()); -V.push_back (root->val); - V.insert (V.end (), Right.begin (), Right.end ()); - + returnv; - } +};
2. Non-recursive algorithm:
A first put the left subtree all in, and then start to play, access to it, and then put its right sub-tree pressure in, actually started to bounce out of time, that point can be regarded as a child, can also be seen as the root. So it's left-"root" right
1 classSolution {2 Public:3vector<int> Inordertraversal (treenode*root) {4vector<int>v;5 if(Root = =NULL)6 returnv;7TreeNode * p =Root;8Stack<treenode*>s;9 while(P)Ten { One while(p)//keep the tree on the left in the press. A { - S.push (p); -p = p->Left ; the } - while(!s.empty ())//Pop a dot to see if there is no right child, there are words to take out as root to traverse - { -TreeNode * cur =s.top (); + S.pop (); -V.push_back (cur->val); + if(cur->Right ) A { atp = cur->Right ; - Break; - } - } - } - returnv; in } -};
B with a bit to mark, the root has not been traversed. If it was 0, it was not traversed, and his right child and his left child were put in. If 1 is traversed, then the output is processed directly.
This method is relatively simple, but also faster, recommended memory.
1 classSolution {2 Public:3vector<int> Inordertraversal (treenode*root) {4std::vector<int>v;5 if(Root = =NULL)6 returnv;7 if(Root->left = = NULL && root-right = =NULL) {8V.push_back (root->val);9 returnv;Ten } OneStack <pair<treenode*,int> >s; AS.push (Make_pair (Root,0)); - while(!s.empty ()) - { theTreeNode * p =S.top (). First; - intindex =S.top (). Second; - S.pop (); - if(!index) + { - if(p->Right ) +S.push (Make_pair (P->right,0)); AS.push (Make_pair (P,1)); at if(p->Left ) -S.push (Make_pair (P->left,0)); -}Else { -V.push_back (p->val); - } - } in returnv; - } to};
Leetcode 94 Binary Tree inorder Traversal