106. Construct Binary Tree from Inorder and Postorder Traversal
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3] 3
/ \
9 20
/ \
15 7/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return build(postorder, postorder.length - 1, inorder, 0, inorder.length -1);
}
private TreeNode build(int[] postorder, int posIdx, int[] inorder, int inStart, int inEnd){
if(inStart > inEnd || posIdx < 0) return null;
TreeNode root = new TreeNode(postorder[posIdx]);
int i = 0;
for(i = inStart; i <= inEnd; i ++){
if(inorder[i] == postorder[posIdx]) break;
}
root.right = build(postorder, posIdx - 1, inorder, i + 1, inEnd);
root.left = build(postorder, posIdx - 1 - (inEnd - i), inorder, inStart, i - 1);
return root;
}
}Last updated
Was this helpful?