Created
January 24, 2015 20:40
-
-
Save Maggie199/d04afd6fff163b3f18e1 to your computer and use it in GitHub Desktop.
Leetcode #106
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[] inorder, int[] postorder) { | |
int in_len = inorder.length; | |
int post_len = postorder.length; | |
if(post_len == 0) | |
return null; | |
TreeNode root=new TreeNode(postorder[post_len-1]); | |
int position=in_len-1; | |
while(inorder[position] != postorder[post_len-1]){ | |
position--; | |
} | |
if(position<in_len-1){ | |
int[] inorder_right_sub = Arrays.copyOfRange(inorder, position+1, in_len); | |
int[] post_right_sub = Arrays.copyOfRange(postorder, position, post_len-1); | |
root.right = buildTree(inorder_right_sub, post_right_sub); | |
} | |
if(position>0){ | |
int[] inorder_left_sub = Arrays.copyOfRange(inorder, 0, position); | |
int[] post_left_sub = Arrays.copyOfRange(postorder, 0, position); | |
root.left = buildTree(inorder_left_sub, post_left_sub); | |
} | |
return root; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment