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

题目来源:LeetCode
根据一棵树的前序遍历与中序遍历构造二叉树。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length == 0){        //判断树是否为空
            return null;
        }
        int rootValue = preorder[0];     //根结点就是前序遍历preorder的第一个元素
        int LeftCount;                   
        for(LeftCount = 0; LeftCount < inorder.length; LeftCount++){
            if(inorder[LeftCount] == rootValue){//在中序遍历inorder中找到根结点
                break;
            }
        }
        TreeNode root = new TreeNode(rootValue);     //将根结点的值装入结点
        //将preorder中的元素从preorder[1]到preorder[1 + LeftCount](左闭右开,不包括后者)拷贝到新的数组leftPreorder中
        int[] leftPreorder = Arrays.copyOfRange(preorder, 1, 1 + LeftCount);
        //将inorder中的元素从inorder[0]到inorder[LeftCount]拷贝到leftInorder中
        int[] leftInorder = Arrays.copyOfRange(inorder, 0, LeftCount);
        //递归
        root.left = buildTree(leftPreorder,leftInorder);
        //同理,写出右子树的过程
        int[] rightPreorder = Arrays.copyOfRange(preorder, LeftCount + 1, preorder.length);
        int[] rightInorder = Arrays.copyOfRange(inorder, LeftCount + 1, inorder.length);
        root.right = buildTree(rightPreorder,rightInorder);
        return root;
    }
}

同理可写出从中序与后序遍历序列构造二叉树的代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder.length == 0){
            return null;
        } 
        int rootValue = postorder[postorder.length - 1];
        int LeftCount;
        for(LeftCount = 0; LeftCount < inorder.length; LeftCount++){
            if(inorder[LeftCount] == rootValue){
                break;
            }
        }
        TreeNode root = new TreeNode(rootValue);
        //这里注意Arrays.copyOfRange()方法拷贝时的范围是:左闭右开
        int[] leftInorder = Arrays.copyOfRange(inorder, 0, LeftCount);
        int[] leftPostorder = Arrays.copyOfRange(postorder, 0, LeftCount);
        root.left = buildTree(leftInorder, leftPostorder);
        int[] rightInorder = Arrays.copyOfRange(inorder, LeftCount + 1, postorder.length);
        int[] rightPostorder = Arrays.copyOfRange(postorder, LeftCount, postorder.length - 1);
        root.right = buildTree(rightInorder, rightPostorder);
        return root;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值