106. 从中序与后序遍历序列构造二叉树(leetcode)

https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

要点是明白中序和后序如何构造二叉树的,并且需要理清当前递归函数的语义,不要一开始就陷入细节,而是思考整棵树与其左右子树的关系,语义是:即构造当前节点,给当前节点左右子树赋值,明白函数的这个语义,利用递归复用这个功能(类似dp子集推大集合,假设子问题已经被解决了,使用子问题推导原问题即可),返回节点即可,剩下的就是处理边界条件和逻辑处理

 

以下是

class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(postorder.length == 0 || inorder.length == 0)
            return null;
        return bulid(inorder, postorder , 0, inorder.length, 0, postorder.length);
    }

    // 左闭右开
    private TreeNode bulid(int[] inorder,int[] postorder,int inStart,int inEnd,int poStart,int poEnd)
    {
        if(inStart==inEnd)return null;
        TreeNode root = new TreeNode(postorder[poEnd-1]);
        int mid=0;
        for(int i=0;i<inEnd;i++)
            if(root.val==inorder[i])
            {
                mid = i;
                break;
            }
        // 分割先序的左右子树
        int leftInorderStart = inStart;
        int leftInorderEnd = mid;
        int rightInorderStart = mid+1;
        int rightInorderEnd = inEnd;
        // 分割后序的左右子树
        int leftPostorderStart = poStart;
        // leftInorderEnd-leftInorderStart 是先序左子树长度
        int leftPostorderEnd = poStart+leftInorderEnd-leftInorderStart;
        int rightPostorderStart = leftPostorderEnd;
        // 后序最后一位需删除,因此poEnd-1
        int rightPostorderEnd = poEnd-1;
        root.left = bulid(inorder,postorder,leftInorderStart,leftInorderEnd,leftPostorderStart,leftPostorderEnd);
        root.right = bulid(inorder,postorder,rightInorderStart,rightInorderEnd,rightPostorderStart,rightPostorderEnd);
        return root;
    }

}

 

posted @ 2024-05-05 11:35  风乐  阅读(42)  评论(0)    收藏  举报