Created
January 25, 2015 05:14
-
-
Save Maggie199/efdea49920e765a27bf9 to your computer and use it in GitHub Desktop.
Leetcode #105
This file contains 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
import java.util.Arrays; | |
public class Solution { | |
public TreeNode buildTree(int[] preorder, int[] inorder) { | |
int len = preorder.length; | |
if(len == 0){ | |
return null; | |
} | |
return buildTreeHelper(preorder, inorder, 0, len-1, 0, len-1); | |
} | |
public TreeNode buildTreeHelper(int[] preorder, int [] inorder, int ps, int pe, int is, int ie){ | |
TreeNode root = new TreeNode(preorder[ps]); | |
int position = is; | |
int len=0; | |
while(inorder[position] != root.val && position <= ie){ | |
position++; | |
len++; | |
} | |
if(position>is) | |
root.left = buildTreeHelper(preorder, inorder, ps+1, ps+len, is, position-1); | |
if(position<ie) | |
root.right = buildTreeHelper(preorder, inorder, ps+len+1, pe, position+1, ie); | |
return root; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment