Construct Binary Tree from inorder and Postorder traversal

Source: Internet
Author: User

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

Constructs a binary tree based on the middle sequence (left root right) and post-order traversal of the tree

Reference: http://www.cnblogs.com/remlostime/archive/2012/10/29/2744738.html

The last element of the post-order traversal is the root node, which divides the middle sequence traversal array into two arrays through the root node, which is a collection of Saozi right sub-tree nodes, which are recursively called

Use the subscript here to save space

1  Public classSolution {2      PublicTreeNode Buildtree (int[] inorder,int[] postorder) {3 TreeNode Root;4         if(0 = =inorder.length)5             return NULL;6         Else 7             returnCreatetree (inorder, postorder, 0, inorder.length-1, 0, Postorder.length-1);8         9     }Ten     PrivateTreeNode Createtree (int[]inorder,int[] Postorder,intInstart,intInend,intPoststart,intpostend) { One         if(Instart >inend) A             return NULL; -         intValue_root = Postorder[postend];//the value of the root node -         intindex = 0;//The index value of the root node in the middle sequence traversal the          for(inti = Instart; I <= inend; i++) {//find the index value of the root node in the final traverse -             if(Postorder[postend] = =Inorder[i]) { -index =i; -                  Break; +             } -         } +         intLength_lefttree = Index-instart;//Length of Zuozi ATreeNode lefttreeroot = Createtree (inorder, Postorder, Instart, Index-1, Poststart, Poststart + length_lefttree-1);  atTreeNode righttreeroot = Createtree (inorder, Postorder, index + 1, inend, Poststart + length_lefttree, postEnd-1); -          -TreeNode root =NewTreeNode (value_root); -          -Root.left =Lefttreeroot; -Root.right =Righttreeroot; in          -         returnRoot; to     } +}

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.