LeetCode——剑指 Offer 07. 重建二叉树

剑指 Offer 07. 重建二叉树

题目

输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

 

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解思路

1>源代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */


// 递归
class Solution {

    private Map<Integer, Integer> index;

    public TreeNode singlebuildTree(int[] preorder, int[] inorder, int pre_left, int pre_right, int in_left, int in_right){
        if(pre_left>pre_right || in_left>in_right){
            return null;
        }
        
        int pre_root = pre_left;
        int in_root = index.get(preorder[pre_root]);
        TreeNode root = new TreeNode(preorder[pre_root]);
        int size_left = in_root - in_left;

        root.left = singlebuildTree(preorder, inorder, pre_left+1, pre_left+size_left, in_left, in_root-1);
        root.right = singlebuildTree(preorder, inorder, pre_left+size_left+1, pre_right, in_root+1, in_right);
        return root;

    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int len = preorder.length;
        index = new HashMap<Integer, Integer>();
        for(int i=0;i<len;i++){
            index.put(inorder[i], i);
        }
        return singlebuildTree(preorder, inorder, 0, len-1, 0, len-1);
    }
}


// 官方迭代
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || preorder.length == 0) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[0]);
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        stack.push(root);
        int inorderIndex = 0;
        for (int i = 1; i < preorder.length; i++) {
            int preorderVal = preorder[i];
            TreeNode node = stack.peek();
            if (node.val != inorder[inorderIndex]) {
                node.left = new TreeNode(preorderVal);
                stack.push(node.left);
            } else {
                while (!stack.isEmpty() && stack.peek().val == inorder[inorderIndex]) {
                    node = stack.pop();
                    inorderIndex++;
                }
                node.right = new TreeNode(preorderVal);
                stack.push(node.right);
            }
        }
        return root;
    }
}

// 作者:LeetCode-Solution
// 链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/solution/mian-shi-ti-07-zhong-jian-er-cha-shu-by-leetcode-s/
// 来源:力扣(LeetCode)
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

// 我的迭代
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length==0){
            return null;
        }
        TreeNode root = new TreeNode(preorder[0]);
        Stack<TreeNode> stack = new Stack<TreeNode>();
        int i;
        int index=0;
        stack.push(root);
        for(i=1;i<preorder.length;i++){
            int pre_val = preorder[i];
            TreeNode temp = stack.peek();
            if(temp.val!=inorder[index]){
                temp.left = new TreeNode(pre_val);
                stack.push(temp.left);
            }
            else{
                while(!stack.isEmpty() && stack.peek().val==inorder[index]){
                    temp = stack.pop();
                    index++;
                }
                temp.right = new TreeNode(pre_val);
                stack.push(temp.right);
            }

        }
        return root;
        

    }
}

2>算法介绍

递归

​在做本题之前,我一直处在一种半懂不懂的阶段.我清晰地记得算法课老师告诉我们,先序+中序可以决定一棵树、中序+后序可以决定一棵树。但在算法课结课后,我就已经忘记了反序列化的步骤,今天算是重新捡回来吧。

这道题有两种解题方法,递归与迭代,其中递归法相对来说比较直观。

递归法的思想是,将先序、中序序列分为三个部分:根、左子树、右子树。那么根据先序和中序的特点,两个序列应该分别为如下结构:

[根, [左子树先序], [右子树先序]]

[[左子树中序], 根, [右子树中序]]

想明白了以上步骤,接下来我们要做的就是构造递归。

public TreeNode singlebuildTree(int[] preorder, int[] inorder, int pre_left, int pre_right, int in_left, int in_right){
        if(pre_left>pre_right || in_left>in_right){
            return null;
        }
        
        int pre_root = pre_left;
        int in_root = index.get(preorder[pre_root]);
        TreeNode root = new TreeNode(preorder[pre_root]);
        int size_left = in_root - in_left;

        root.left = singlebuildTree(preorder, inorder, pre_left+1, pre_left+size_left, in_left, in_root-1);
        root.right = singlebuildTree(preorder, inorder, pre_left+size_left+1, pre_right, in_root+1, in_right);
        return root;

    }

总体来说还是比较清晰的,相信看过代码之后就能掌握递归法的构造思路。本题的亮点在于迭代法。


迭代

思路

迭代法是一种非常巧妙的实现方法。

对于前序遍历中的任意两个连续节点 u 和 v,根据前序遍历的流程,我们可以知道 u 和 v 只有两种可能的关系:

v 是 u 的左儿子。这是因为在遍历到 u 之后,下一个遍历的节点就是 u 的左儿子,即 v;

u 没有左儿子,并且 v 是 u 的某个祖先节点(或者 u 本身)的右儿子。如果 u 没有左儿子,那么下一个遍历的节点就是 u 的右儿子。如果 u 没有右儿子,我们就会向上回溯,直到遇到第一个有右儿子(且 u 不在它的右儿子的子树中)的节点 u_a,那么 v 就是 u_a的右儿子。

算法

我们归纳出上述解释中的算法流程:

我们用一个栈和一个指针辅助进行二叉树的构造。初始时栈中存放了根节点(前序遍历的第一个节点),指针指向中序遍历的第一个节点;

我们依次枚举前序遍历中除了第一个节点以外的每个节点。如果 index 恰好指向栈顶节点,那么我们不断地弹出栈顶节点并向右移动 index,并将当前节点作为最后一个弹出的节点的右儿子;如果 index 和栈顶节点不同,我们将当前节点作为栈顶节点的左儿子;

无论是哪一种情况,我们最后都将当前的节点入栈。

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/solution/mian-shi-ti-07-zhong-jian-er-cha-shu-by-leetcode-s/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


以上为官方文档给出的迭代方法,总得来说就是从先序遍历开始一直往左下走,如果遇到了inorder[index],则说明到了左下角,这时就需要回溯并开始往右下角走。回溯是通过栈结构来完成。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值