刷题笔记《剑指offer》-第四题 ReconstructBinaryTree 重建二叉树

题目描述:

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列
{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

思路:
1. 前序遍历特点:第一个节点是根节点,中序遍历特点:根节点的前面全是左子树节点,后面全是右子树节点
2. 整体思路类似于考研时二叉树重建的选择题
3. 输入的时数组,考虑操作他的下标信息
4. 根据前序序列找到根节点的值,再到中序序列中找到根节点所在的位置,用来确定左子树和右子树
5. 根节点的左指针指向左子树的根节点,右指针指向右子树的根节点,同时递归调用这个方法。
注意点:
	当问题比较复杂的时候,可以考虑使用多个函数解决这个问题。函数的参数不便于我们解决问题时,可以使用一个warpper函数。
代码
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

public class ReConstructBinaryTree {

    public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        int preLength = pre.length;
        int inLength = in.length;

        return reConstructCore(pre, in, 0, preLength-1, 0, inLength-1);
    }

    public static TreeNode reConstructCore(int[] pre, int[] in,
                                           int preStart, int preEnd,
                                           int inStart, int inEnd) {

        int rootValue = pre[preStart]; // 前序遍历的第一个是根节点
        TreeNode r = new TreeNode(rootValue);
        // 在中序遍历中找到他的根节点所在的位置,用它来划分节点簇
        int inRootIdx = inStart;
        while (inRootIdx < inEnd && in[inRootIdx] != rootValue)
            inRootIdx++;

        // 左右子树的长度为
        int leftLength = inRootIdx - inStart;
        int rightLength = inEnd - inRootIdx;
        if(leftLength > 0)
            r.left = reConstructCore(pre, in, preStart+1, preStart+leftLength, inStart, inRootIdx-1);

        if(rightLength > 0)
            r.right = reConstructCore(pre, in, preStart+leftLength+1, preEnd, inRootIdx+1, inEnd);

        return r;

    }

    public static void main(String[] args) {
        int[] pre = new int[]{1, 2, 4, 7, 3, 5, 6, 8};
        int[] in = new int[]{4, 7, 2, 1, 5, 3, 8, 6};

        TreeNode root = reConstructBinaryTree(pre, in);
    }

}
根据费曼学习法: 学习到的东西只有输出了才能巩固得更好。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值