[Leedcode 106] Construct Binary Tree from preorder and inorder traversal

Source: Internet
Author: User

Given Preorder and inorder traversal of a tree, construct the binary tree.

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

/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution {//The preorder and inorder traversals for the binary tree above are:     /*preorder = {7,10,4,3,1,2,8,11} inorder = {4,10,3,1,7,11,8,2} The first node in preorder alwasy the RO OT of the tree. We can break the tree like:1st Round:preorder: {7}, {10,4,3,1}, {2,8,11} inorder: {4,10,3,1},        {7}, {11, 8,2} can be found, a traversal can be an array of two, corresponding to the Zuozi set and the right subtree set using the preorder array positioning with the node, using the Inorder array sub-tree. Key points: 1 Locating the root node of each Layer 2 calculate the offset note the definition of the Gettree function*/     PublicTreeNode Buildtree (int[] Preorder,int[] inorder) {        if(preorder.length!=inorder.length| | preorder.length==0)return NULL; returnGettree (preorder,0,preorder.length-1,inorder,0,inorder.length-1); } TreeNode Gettree (int[] Preorder,intLEFT1,intRIGHT1,int[] inorder,intLEFT2,intright2) {        if(LEFT1&GT;RIGHT1)return NULL; if(LEFT2&GT;RIGHT2)return NULL; inttemp=PREORDER[LEFT1]; TreeNode node=NewTreeNode (temp); intindex=left2;  for(; index<=right2;index++){            if(inorder[index]==temp) Break; }        intlen=index-left2; Node.left=gettree (preorder,left1+1,left1+len,inorder,left2,index-1); Node.right=gettree (preorder,left1+len+1,right1,inorder,index+1, right2); returnnode; }}

[Leedcode 106] Construct Binary Tree from preorder and inorder 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.