【Leetcode】105. 从前序与中序遍历序列构造二叉树

栏目: 数据库 · 发布时间: 6年前

内容简介:根据一棵树的前序遍历与中序遍历构造二叉树。注意:你可以假设树中没有重复的元素。

题目

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:

你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]

中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:

3
   / \
  9  20
    /  \
   15   7

题解

根据前序和中序可以构造一颗二叉树,根据中序和后续也可以构建一颗二叉树。

反正必须要有中序才能构建,因为没有中序,你没办法确定树的形状。

比如先序和后序是不能构建唯一的一颗二叉树的。

例如:

先序为:[1, 2]

后序为:[2, 1]

可以构建如下

1
   / 
  2
1
     \
      2

这个面试官也会问的。

那回到这个题目, 其实思路比较好想到,就是如何划分子问题,然后递归的构建左子树和右子树。

preorder = [3,9,20,15,7]

inorder = [9,3,15,20,7]

因为先序先遍历根节点,可以确定根节点为3;

再根据中序得到:

leftInOrder = [9]

RightInOrder = [15, 20 ,7]

又由于中序和先序的数组大小应该相同的,

所以,

LeftPreOrder = [9]

RightPreOrder = [20, 15, 7]

至此,划分为子问题:

leftInOrder = [9]

LeftPreOrder = [9]

构建左子树。

RightPreOrder = [20, 15, 7]

RightInOrder = [15, 20 ,7]

构建右子树。

/**
 * 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) {
        return helper(preorder, inorder, 0, 0, inorder.length - 1);
    }

    public TreeNode helper(int[] preorder, int[] inorder, int preStart, int inStart, int inEnd) {
        if (inStart > inEnd) {
            return null;
        }
        int currentVal = preorder[preStart];
        TreeNode current = new TreeNode(currentVal);
        
        int inIndex = 0; 
        for (int i = inStart; i <= inEnd; i++) {
            if (inorder[i] == currentVal) {
                inIndex = i;
            }
        }

        TreeNode left = helper(preorder, inorder, preStart + 1, inStart, inIndex - 1);
        TreeNode right = helper(preorder, inorder, preStart + inIndex - inStart + 1, inIndex + 1, inEnd);
        current.left = left;
        current.right = right;
        return current;
    }
}

热门阅读

【Leetcode】105. 从前序与中序遍历序列构造二叉树

手撕代码QQ群:805423079, 群密码:1024


以上所述就是小编给大家介绍的《【Leetcode】105. 从前序与中序遍历序列构造二叉树》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms on Strings, Trees and Sequences

Algorithms on Strings, Trees and Sequences

Dan Gusfield / Cambridge University Press / 1997-5-28 / USD 99.99

String algorithms are a traditional area of study in computer science. In recent years their importance has grown dramatically with the huge increase of electronically stored text and of molecular seq......一起来看看 《Algorithms on Strings, Trees and Sequences》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具