`
huntfor
  • 浏览: 201216 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode]Construct Binary Tree from Inorder and Postorder Traversal

 
阅读更多

新博文地址:

[leetcode]Construct Binary Tree from Inorder and Postorder Traversal

 

Construct Binary Tree from Inorder and Postorder Traversal

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

Note:
You may assume that duplicates do not exist in the tree.

 跟这道题没有任何区别。

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder.length == 0){
            return null;
        }
        if(inorder.length == 1){
            return new TreeNode(inorder[0]);
        }
        TreeNode root = new TreeNode(postorder[postorder.length - 1]);
        int[] leftInorder = getLeftInorder(inorder,postorder[postorder.length - 1]);
        int[] rightInorder = Arrays.copyOfRange(inorder,leftInorder.length + 1,inorder.length);
        int[] leftPostorder = Arrays.copyOf(postorder,leftInorder.length);
        int[] rightPostorder = Arrays.copyOfRange(postorder,leftPostorder.length,postorder.length - 1);
        root.left = buildTree(leftInorder,leftPostorder);
        root.right = buildTree(rightInorder,rightPostorder);
        return root;
    }
    private int[] getLeftInorder(int[] inorder ,int target){
        int length = 0 ;
        for(; length < inorder.length; length++){
            if(inorder[length] == target){
                break;
            }
        }
        return Arrays.copyOf(inorder,length);
    }

 当树中包含重复数字该怎样

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics