Record the available middle-order traversal methods
Method 1:
vector<int> Inordertraverse (TreeNode * root)//Middle Sequence Traversal{vector<int>ans; TreeNode*p; Vector<treenode *>Stack; Stack.push_back (root); while(!Stack.empty ()) { while(P = stack.back ())! =NULL) Stack.push_back (P-Left ); Stack.pop_back (); if(!Stack.empty ()) {P=Stack.back (); Stack.pop_back (); Ans.push_back (P-val); Stack.push_back (P-Right ); } } returnans; }
Method 2:
vector<int> Inordertraversal (TreeNode *root) {Vector<int>Vector; Stack<treenode *>Stack; TreeNode*pcurrent =Root; while(!stack.empty () | |pcurrent) { if(pcurrent) {Stack.push (pcurrent); Pcurrent= pcurrent->Left ; } Else{TreeNode*pnode =Stack.top (); Vector.push_back (Pnode-val); Stack.pop (); Pcurrent= pnode->Right ; } } returnVector; }
I wrote it in my own way, and tuned it many times. The key is the logical confusion when the right subtree pops up.
vector<int> Inordertraversal (TreeNode *root) {Vector<int>ans; Vector<treenode *>v; TreeNode*p; if(Root = NULL)returnans; V.push_back (root); while(!V.empty ()) {P=V.back (); while(P->left! = NULL)//find the left-most{v.push_back (P-Left ); P= p->Left ; } ans.push_back (P->val);//Press-in dataV.pop_back (); while(P->right = = NULL)//right subtree processing if the current right subtree is empty then you need to eject the value of the tail in V { if(!V.empty ()) {P=V.back (); Ans.push_back (P-val); V.pop_back (); } Else { Break; } } if(P->right! =NULL) {V.push_back (P-Right ); } } returnans; }
There is no need to stack the method, using the Clue two fork tree concept, Space complexity O (1)
Http://www.cnblogs.com/AnnieKim/archive/2013/06/15/morristraversal.html
Binary tree traversal in sequence