# leetcode Construct Binary Tree from Preorder and Inorder Traversal

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(inorder==null||inorder.length==0)
{
return null;
}

TreeNode root=new TreeNode(preorder[0]);
build(root, inorder, 0, inorder.length-1, preorder, 0, preorder.length-1);

return root;
}

public void build(TreeNode root,int[] inorder, int ins,int ine,int[] preorder,int pres,int pree)
{
int parentIndexInMiddle=ins;

while(inorder[parentIndexInMiddle]!=root.val)
{
parentIndexInMiddle++;
}

int leftCount=parentIndexInMiddle-ins;

if(leftCount>0)
{
int leftRootIndexInPre=pres+1;
root.left=new TreeNode(preorder[leftRootIndexInPre]);
build(root.left, inorder, ins, parentIndexInMiddle-1, preorder, leftRootIndexInPre, pres+1+leftCount-1);
}

int rightCount=ine-parentIndexInMiddle;
if(rightCount>0)
{
int rightRootIndexInpre=pree-rightCount+1;
root.right=new TreeNode(preorder[rightRootIndexInpre]);
build(root.right, inorder, parentIndexInMiddle+1, ine, preorder, rightRootIndexInpre, pree);
}
}
}

#### 【LeetCode】105. Construct Binary Tree from Preorder and Inorder Traversal 解题报告

2016-06-01 23:42:08

#### 【LeetCode-面试算法经典-Java实现】【105-Construct Binary Tree from Preorder and Inorder Traversal（构造二叉树）】

2015-08-09 06:37:17

#### [LeetCode-21]Construct Binary Tree from Preorder and Inorder Traversal

2014-05-21 05:59:08

#### leetcode笔记：Construct Binary Tree from Preorder and Inorder Traversal

2015-11-30 23:54:21

#### Construct Binary Tree from Preorder and Inorder Traversal -- LeetCode

2014-04-24 08:43:09

#### C++详解Leetcode:105. Construct Binary Tree from Preorder and Inorder Traversal

2017-07-30 17:34:05

#### 【LeetCode-面试算法经典-Java实现】【106-Construct Binary Tree from Inorder and Postorder Traversal（构造二叉树II）】

2015-08-09 06:39:31

#### LeetCode Construct Binary Tree from Inorder and Postorder Traversal 思考分析过程分享

2013-11-12 13:20:50

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

2014-12-04 23:07:11

#### Construct Binary Tree from Inorder and Postorder Traversal -- LeetCode

2014-04-24 09:02:17