0
点赞
收藏
分享

微信扫一扫

LeetCode106. 从中序与后序遍历序列构造二叉树

瑾谋 2022-05-01 阅读 87

思路

根据后序遍历的数组中最后一个元素分隔中序遍历,后序遍历的最后一个元素就是当前节点,

中序遍历的数组根据后序遍历的数组中最后一个元素,将中序数组分为两部分,然后后序遍历的数组也分为对应长度的两部分;

中序数组的左部分和后序数组的左部分的结果是左孩子,中序数组的右部分和后序数组的右部分的结果是右孩子。

注:我的代码中是以数组下标为参数。

代码

/**
 * 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 {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder == null || postorder == null){
            return null;
        }
        TreeNode temp = buildTree1(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
        return temp;
    }
    public TreeNode buildTree1(int[] inorder, int inLeft, int inRight,int[] postorder, int postLeft, int postRight) {
        
        // 没有元素了
        if (inRight - inLeft < 0) {
            return null;
        }
        // 只有一个元素了
        if (inRight - inLeft == 0) {
            return new TreeNode(inorder[inLeft]);
        }
        int rootIndex = 0;
        int rootVal = postorder[postRight];
        postRight--;
        TreeNode root = new TreeNode(rootVal);
        for(int i = inLeft;i<=inRight;i++){
            if(inorder[i] == rootVal){
                rootIndex = i;
                break;
            }
        }
        
        root.left = buildTree1(inorder,inLeft,rootIndex-1,postorder,postLeft,postLeft+rootIndex-inLeft-1);
        root.right = buildTree1(inorder,rootIndex+1,inRight,postorder,postLeft+rootIndex-inLeft,postRight);
        return root;

    }    
}
举报

相关推荐

0 条评论