LeetCode_二叉树_中等_106.从中序与后序遍历序列构造二叉树

x33g5p2x  于2022-03-28 转载在 其他  
字(1.4k)|赞(0)|评价(0)|浏览(409)

1.题目

给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。

示例 1:

输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]

示例 2:
输入:inorder = [-1], postorder = [-1]
输出:[-1]

提示:

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal

2.思路

(1)分治算法
参考二叉树(构造篇)

3.代码实现(Java)

//思路1————分治算法
/**
 * 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) {
        return build(inorder, 0, inorder.length - 1,
                postorder, 0, postorder.length - 1);
    }
    
    /*
        中序遍历数组为 inorder[inStart...inEnd]
        后序遍历数组为 postorder[postStart...postEnd]
        构造这个二叉树并返回该二叉树的根节点
    */
    public TreeNode build(int[] inorder, int inStart, int inEnd,
                          int[] postorder, int postStart, int postEnd) {
        if (inStart > inEnd) {
            return null;
        }
        //后序遍历数组的最后一个元素就是root节点对应的值
        int rootVal = postorder[postEnd];
        //找出rootVal在中序遍历数组中的索引
        int index = 0;
        for (int i = inStart; i <= inEnd; i++) {
            if (inorder[i] == rootVal) {
                index = i;
                break;
            }
        }
        int leftSize = index - inStart;
        //构造当前根节点
        TreeNode root = new TreeNode(rootVal);
        //递归构造左右子树
        root.left = build(inorder, inStart, index - 1,
                postorder, postStart, postStart + leftSize - 1);
        root.right = build(inorder, index + 1, inEnd,
                postorder, postStart + leftSize, postEnd - 1);
        return root;
    }
}

相关文章