Created
March 10, 2013 03:00
-
-
Save guolinaileen/5126917 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for binary tree | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
public class Solution { | |
public TreeNode buildTree(int[] preorder, int[] inorder) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
if(preorder.length==0 || inorder.length==0) return null; | |
return buildTree(inorder, 0, inorder.length-1, preorder, 0, preorder.length-1); | |
} | |
TreeNode buildTree(int [] inorder, int startI, int endI, int[] preorder, int startP, int endP) | |
{ | |
if(startI>endI || startP>endP) return null; | |
if(startI==endI) return new TreeNode(inorder[startI]); | |
if(startP==endP) return new TreeNode(preorder[startP]); | |
int indexIn=findOrder(startI, endI, inorder, preorder[startP]); | |
if(indexIn==-1) return null; | |
TreeNode root=new TreeNode(inorder[indexIn]); | |
root.left= buildTree(inorder, startI, indexIn-1, preorder, startP+1, indexIn-startI+startP ); | |
root.right= buildTree(inorder, indexIn+1, endI, preorder, indexIn-startI+startP+1, endP ); | |
return root; | |
} | |
int findOrder(int start, int end, int [] inorder, int target) | |
{ | |
for(int i=start; i<=end; i++) | |
{ | |
if(inorder[i]==target) return i; | |
} | |
return -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment