皮皮的LeetCode刷题库

【剑指Offer】04——重建二叉树 (树)

2019-08-17  本文已影响0人  就问皮不皮

题目描述

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

解题思路

我们知道,前序遍历的第一个节点就是树的根节点,所以我们先根据前序遍历序列的第一个数字创建根结点,接下来在中序遍历序列中找到根结点的位置(无重复数字的作用),根节点的左边就是左子树,右边就是右子树,这样就能确定左、右子树结点的数量。在前序遍历和中序遍历的序列中划分了左、右子树结点的值之后,就可以递归地去分别构建它的左右子树。


image

先序遍历:先打印头节点,再打印左节点,然后打印右节点(头-->左-->右)

中序遍历:左->头->右

参考代码

Java

/*
* 无重复数字便于寻找
*/
    // Definition for binary tree
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) {
            this.val = x;
        }
    }

    /**
     * 
     * @param pre 前序遍历数组
     * @param in  中序遍历数组
     * @return
     */
    public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        if (pre.length == 0 || in.length == 0)
            return null;
        // 主根
        return ConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);

    }

    /**
     * 
     * @param pre 前序遍历数组
     * @param ps  起始值(pre start)
     * @param pe  前序数组的索引最大值
     * @param in  中序遍历数组
     * @param is  起始值(in start)
     * @param ie  中序数组的索引最大值
     * @return
     */
    public TreeNode ConstructBinaryTree(int[] pre, int ps, int pe, int[] in, int is, int ie) {
        // 递归截至条件
        if (ps > pe || is > ie) {
            return null;
        }
        TreeNode root = new TreeNode(pre[ps]); // 根据前向数组获取根节点
        // 遍历查找在中序中的根
        for (int i = is; i <= ie; i++) {
            // 获取索引
            if (in[i] == pre[ps]) {
                root.left = ConstructBinaryTree(pre, ps + 1, ps + i - is, in, is, i - 1);
                root.right = ConstructBinaryTree(pre, ps + i - is + 1, pe, in, i + 1, ie);
                break;
            }
        }
        return root;
    }

Python

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        if not pre:
            return None
        root = TreeNode(pre[0])
        i = tin.index(pre[0])
        root.left = self.reConstructBinaryTree(pre[1:i+1], tin[:i])
        root.right = self.reConstructBinaryTree(pre[i+1:], tin[i+1:])
        return root

个人订阅号

image
上一篇 下一篇

猜你喜欢

热点阅读