leetcode: 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.

解题思路:

  1. 涉及到二叉树的问题都是考虑用递归树来解决
  2. 观察中序遍历和后续遍历,我们不难发现后序遍历中的最后一位就是根节点的值
  3. 找到根节点的之后,我们再在前序遍历数组中找到根节点的值,将其一分为二,剩下的事情就交给递归来做

代码如下:

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int inLength = inorder.length;
        int postLength = postorder.length;

	// 对输入的数组进行简单的判断
        if(inLength != postLength) return null;
		
	// 递归结束的条件
        if(inLength < 1 || postLength < 1) return null;

	// 递归体
        TreeNode root = new TreeNode(postorder[postLength - 1]);
        for(int i = 0; i < inLength; i++){
            if(inorder[i] == postorder[postLength - 1]){
                root.left = buildTree(Arrays.copyOfRange(inorder,0,i),
                        Arrays.copyOfRange(postorder,0,i));

                root.right = buildTree(Arrays.copyOfRange(inorder,i + 1,inLength),
                        Arrays.copyOfRange(postorder,i,postLength - 1));
            }
        }
        return root;
    }

转载于:https://my.oschina.net/happywe/blog/3092664

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值