"Binary tree Traversal" in sequence

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.