从中序与后序遍历序列构造二叉树——leetcode106

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

题目:从中序与后序遍历序列构造二叉树

根据一棵树的中序遍历与后序遍历构造二叉树。

示例:

    3
   / \
  9  20
    /  \
   15   7
输入:中序遍历 inorder = [9,3,15,20,7],后序遍历 postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]

题解

 class Solution {
        private int in[];
        private int post[];
        
        public TreeNode dfs(int ileft, int iright, int pleft, int pright)
        {
            if(iright<ileft || pright<pleft) return null;
            int val=post[pright];
            int x=0;
            for(int i=ileft; i<=iright; i++) {
                if (in[i] == val) {
                    x = i;
                    break;
                }
            }
            TreeNode root=new TreeNode(val);
            root.left=dfs(ileft, x-1, pleft, pleft+x-ileft-1);
            root.right=dfs(x+1, iright, pleft+x-ileft, pright-1);
            return root;
        }
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            in=inorder;
            post=postorder;
            
            return dfs(0, inorder.length-1, 0, postorder.length-1);
        }
    }
posted @ 2021-12-29 12:55  言思宁  阅读(21)  评论(0编辑  收藏  举报