Created
April 27, 2013 07:42
-
-
Save daifu/5472237 to your computer and use it in GitHub Desktop.
Construct Binary Tree from Inorder and Postorder Traversal
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
/* | |
Given inorder and postorder traversal of a tree, construct the binary tree. | |
Note: | |
You may assume that duplicates do not exist in the tree. | |
*/ | |
/** | |
* 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[] inorder, int[] postorder) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
if(inorder.length == 0) return null; | |
return buildTreeHelper(inorder, postorder, 0, inorder.length-1, 0, postorder.length-1); | |
} | |
public TreeNode buildTreeHelper(int[] inorder, int[] postorder, int in_s, int in_e, int po_s, int po_e) { | |
if(po_e < po_s) return null; | |
int end = postorder[po_e]; | |
po_e--; | |
TreeNode root = new TreeNode(end); | |
int len = 0; | |
for(int i = in_e; i > in_s; i--) { | |
if(inorder[i] == end) break; | |
len++; | |
} | |
root.left = buildTreeHelper(inorder, postorder, in_s, in_e-len-1, po_s, po_e-len); | |
root.right = buildTreeHelper(inorder, postorder, in_e-len+1, in_e, po_e-len+1, po_e); | |
return root; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment