106. Construct Binary Tree from Inorder and Postorder Traversal

Medium

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

思路跟之间拿到inorder + preorder construct binary tree基本是一样的思路。根据postorder里最后面的是root的规律,我们维持一个postIndex从后面往前依次遍历postorder. 每次指向某个postorder里的元素,那我们就构建一个以该元素的值为val的tNode. 再去inorder里面找到这个tNode.val, 得到inIndex. 这样我们就可以把inorder里剩下的元素分为tNode的左右子树。inorder里在inIndex前面的在tNode的左子树,inIndex后面的在tNode的右子树。那么我们就可以分别在左右两边依次递归,要注意每次递归锁定的范围,可以用start, end来固定,并注意每次更新的规律。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int postIndex = 0;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder == null || postorder == null || inorder.length == 0 || postorder.length == 0){
            return null;
        }
        postIndex = postorder.length - 1;
        return helper(inorder, postorder, 0, inorder.length - 1);
    }
    
    private TreeNode helper(int[] inorder, int[] postorder, int start, int end){
        if (start > end || postIndex < 0){
            return null;
        }
        TreeNode tNode = new TreeNode(postorder[postIndex--]);
        int inIndex = search(inorder, tNode.val, start, end);
        tNode.right = helper(inorder, postorder, inIndex + 1, end);  
        tNode.left = helper(inorder, postorder, start, inIndex - 1);
        return tNode;
    }
    
    private int search(int[] inorder, int target, int left, int right){
        for (int i = left; i <= right; i++){
            if (inorder[i] == target){
                return i;
            }
        }
        return -1;    
    }
}

你可能感兴趣的:(106. Construct Binary Tree from Inorder and Postorder Traversal)