Created
August 28, 2017 00:29
-
-
Save cixuuz/2eaa7c1745b77997a75175e0be66444e to your computer and use it in GitHub Desktop.
[106. Construct Binary Tree from Inorder and Postorder Traversal] #leetcode
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
class Solution { | |
public TreeNode buildTree(int[] inorder, int[] postorder) { | |
return dfs(inorder, postorder, inorder.length-1, 0, inorder.length-1); | |
} | |
private TreeNode dfs(int[] inorder, int[] postorder, int postInd, int leftIn, int rightIn) { | |
if ( leftIn > rightIn || postInd < 0 ) return null; | |
int value = postorder[postInd]; | |
TreeNode node = new TreeNode(value); | |
int tmp = 0; | |
for (int i = 0; i < inorder.length; i++) { | |
if (inorder[i] == value) { | |
tmp = i; | |
break; | |
} | |
} | |
node.right = dfs(inorder, postorder, postInd-1, tmp+1, rightIn); | |
node.left = dfs(inorder, postorder, postInd-(rightIn - tmp + 1), leftIn, tmp-1); | |
return node; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment