As postorder traversal meet left and right children before root, we may know that the last element in postorder array must be the root. Based on this pattern, I can see that for subtree of root, whatever left one or right one, it must follow this pattern too. And we also know that in inorder array, elements before one particular element are on the left side of it, those after it on the right side, in the tree structure. So we continue this pattern on root's left subtree, and right subtree recursively, if exist.
One thing to notice is that the variable "del". This is the value we need to move leftwards when we are playing with right subtree. Each time we deal with right subtree, indexes of right subtree in inorder array should be minus by one, since root element must be left of right subtree in inorder array, and we use relative index of root to determine which part is left subtree, which is right. This variable "del" might can be used to perform so-called "calibration"
/**
* 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) {
if(inorder.length != postorder.length || inorder.length < 1){
return null;
}
if(inorder.length == 1){
return new TreeNode(inorder[0]);
}
TreeNode root = constructTree(inorder,postorder,0,inorder.length - 1,0);
return root;
}
private TreeNode constructTree(int[] inorder, int[]postorder,int low,int up, int del){
if(low<=up){
TreeNode root = new TreeNode(postorder[up]);
int inIdx = Math.min(up, findInIdx(inorder,postorder[up]) - del);
TreeNode left = constructTree(inorder, postorder,low,inIdx - 1,del);
TreeNode right = constructTree(inorder, postorder,inIdx,up - 1,del + 1);
root.left = left;
root.right = right;
return root;
}
else return null;
}
private int findInIdx(int[] arr, int val){
for(int i=0;i < arr.length; i ++){
if(arr[i] == val) return i;
}
return -1;
}
}
No comments:
Post a Comment