Created
August 28, 2013 00:30
-
-
Save charlespunk/6360780 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
Given inorder and postorder traversal of a tree, construct the binary tree. | |
Note: | |
You may assume that duplicates do not exist in the tree. |
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[] inorder, int[] postorder) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
return buildTree(0, inorder.length - 1, 0, postorder.length - 1, | |
inorder, postorder); | |
} | |
public TreeNode buildTree(int inBegin, int inEnd, int posBegin, int posEnd, | |
int[] inorder, int[] postorder){ | |
if(posBegin > posEnd) return null; | |
int mid = inBegin; | |
for(; mid <= inEnd; mid++) if(postorder[posEnd] == inorder[mid]) break; | |
TreeNode parent = new TreeNode(inorder[mid]); | |
parent.left = buildTree(inBegin, mid - 1, posBegin, posBegin + mid - inBegin - 1, | |
inorder, postorder); | |
parent.right = buildTree(mid + 1, inEnd, posBegin + mid - inBegin, posEnd - 1, | |
inorder, postorder); | |
return parent; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment