rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

106. 从中序与后序遍历序列构造二叉树 #71

Open rocksc30 opened 1 year ago

rocksc30 commented 1 year ago
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private Map<Integer, Integer> map = new HashMap<>();
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int n = inorder.length;
        for(int i = 0; i < n; i++){
            map.put(inorder[i], i);
        }
        return helper(inorder, 0, n, postorder, 0, n);
    }
    public TreeNode helper(int[] inorder, int inStart, int inEnd
        , int[] postorder, int postStart, int postEnd){

        if(inStart >= inEnd || postStart >= postEnd){
            return null;
        }
        int rootIndex = map.get(postorder[postEnd - 1]);
        TreeNode root = new TreeNode(postorder[postEnd - 1]);
        int lenOfLeft = rootIndex - inStart;
        root.left = helper(inorder, inStart, rootIndex, postorder, postStart, postStart + lenOfLeft);
        root.right = helper(inorder, rootIndex + 1, inEnd, postorder, postStart + lenOfLeft, postEnd - 1);
        return root;
    }
}