106. Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:英文翻译什么软件好 编辑:程序博客网 时间:2024/06/07 11:30

Given inorder and postorder traversal of a tree, construct the binary tree.

这道题与其前一道题的思路是近似的,不同的是对于后序数组我们需要从后向前操作,这其中我们可以利用一个HashMap进行查找时间上的加速,代码如下:

public TreeNode buildTree(int[] inorder, int[] postorder) {
        // 特殊情况处理
        if(inorder == null || inorder.length == 0 || postorder.length == 0 || postorder == null || inorder.length != postorder.length){
            return null;
        }
        
        Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
        for(int i = 0; i < inorder.length; i++){
            hashMap.put(inorder[i], i);
        }
        
        return buildResultTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1, hashMap);
    }
    
    private TreeNode buildResultTree(int[] inorder, int inoLeft, int inoRight, int[] postorder, int posLeft, int posRight, Map<Integer, Integer> hashMap){
        if(posLeft > posRight){
            return null;
        }
        TreeNode treeNode = new TreeNode(postorder[posRight]);
        int index = hashMap.get(postorder[posRight]);
        treeNode.left = buildResultTree(inorder, inoLeft, index - 1, postorder, posLeft, posRight - (inoRight - index) - 1, hashMap);
        treeNode.right = buildResultTree(inorder, index + 1, inoRight, postorder, posRight - (inoRight - index), posRight - 1, hashMap);
        return treeNode;
    }

0 0
原创粉丝点击