Leetcode 106. Construct Binary Tree from inorder and Postorder traversal

Source: Internet
Author: User

106. Construct Binary Tree from inorder and Postorder traversal
    • Total accepted:60461
    • Total submissions:203546
    • Difficulty:medium

Given Inorder and Postorder traversal of a tree, construct the binary tree.

Note:
Assume that duplicates does not exist in the tree.

Subscribe to see which companies asked this question

Idea: By the sequence of the tree and post-order achievements, you can use recursion and iteration.

Code:
Recursive form: 156 ms

The idea is straightforward, that is, recursive achievements.

1  /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8  * };9  */Ten classSolution { One  Public: Atreenode* Buildtree (vector<int>& Inorder, vector<int>& postorder) {//Middle and post order -         if(postorder.size () = =0){ -             returnNULL; the         } -         inti,n=postorder.size (); -treenode* root=NewTreeNode (Postorder.back ()); -vector<int>Rightinorder,rightpostorder; +          for(i=0; I<n&&inorder[i]!=postorder.back (); i++); -Inorder.erase (Inorder.begin () +i); + Postorder.pop_back (); A          while(i<inorder.size ()) { at Rightinorder.push_back (Inorder[i]); -Inorder.erase (Inorder.begin () +i); - Rightpostorder.push_back (Postorder[i]); -Postorder.erase (Postorder.begin () +i); -         } -root->left=Buildtree (inorder,postorder); inroot->right=Buildtree (rightinorder,rightpostorder); -         returnRoot; to     } +};

Iteration form: MS

Reference: HTTPS://DISCUSS.LEETCODE.COM/TOPIC/4746/MY-COMPREHENSION-OF-O-N-SOLUTION-FROM-HONGZHI/2

The original text reads as follows:

Below isThe O (n) solution from@hongzhi but that discuss isClosed Now'cause @hongzhi says little about his code.https://oj.leetcode.com/discuss/6334/here-is-my-o-n-solution-is-it-neatI've modified some of and tried this code and got AC.Just share about some comprehension on his code. I've modified vtn (vector) to STN (stack) on that stack are probably what the this algs means and needs.What is matters most isThe meaning of STN. Only nodes Whoes left side hasn'T been handled is pushed into STN.and inorder isOrganized as(Inorder of left) root (Inorder of right), and Postorder is  as(Postorder of left) (Postorder of right) root. So at the very begin, we are only having rootinchSTN and we checkifInorder.back () = = Root->val andinchMost cases it's False (see Note 1). Then we do this node root's right sub-node and push it into STN. Note1: This  isActually (inorder of right). Back () = = (Postorder of right). Back (), soifOnly there's no right subtree or the answer would always be false.Note2: We delete one node fromPostorder aswe push one into STN. Now we have [root, root's right] as STN and we check inorder.back () = = Stn.top ()->val again.trueMeans Inorder.back () isThe root node and needs handled left Case.falseMeans Inorder.back () isThe next right sub-Nodeso When we encounter atrue, we'll cache Stn.top () asP and Delete both nodes frominorder and STN. Then we check inorder.size (),ifThere's no nodes left, it means p have no left node.Else the next nodeinchInorder could be p's left node or P's father which equals to the now stn.top (remember we popped P fromSTN above). If The latter happens, it means p have no left node and we need to move on to P's father (Stn.top ()).If The former happens, it means p have one left node and it's Postorder.back (), so we put it to P's left and delete it fromThe postorder and push the left node into STN'cause it should be the next check node as the Postorder is organized as above.

1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8  * };9  */Ten classSolution { One  Public: Atreenode* Buildtree (vector<int>& Inorder, vector<int>& postorder) {//Middle and post order -Stack<treenode*>s; -         if(postorder.size () = =0){ the             returnNULL; -         } -treenode* root=NewTreeNode (Postorder.back ()); -treenode*p; + Postorder.pop_back (); - S.push (root); +          while(true){ A             if(S.top ()->val==Inorder.back ()) { atp=s.top (); - S.pop (); - Inorder.pop_back (); -                 if(inorder.size () = =0) Break; -                 if(!s.empty () &&inorder.back () ==s.top ()->val)Continue;//p Whether there are left dial hand trees -treenode* temp=NewTreeNode (Postorder.back ()); inp->left=temp; - S.push (temp); to Postorder.pop_back (); +             } -             Else{ thetreenode* temp=NewTreeNode (Postorder.back ()); *S.top ()->right=temp; $ S.push (temp);Panax Notoginseng Postorder.pop_back (); -             } the         } +         returnRoot; A     } the};

Leetcode 106. Construct Binary Tree from inorder and postorder traversal

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.