【Leetcode】106. 从中序与后序遍历序列构造二叉树2

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

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

题目

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

注意:

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

例如,给出

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

后序遍历 postorder = [9,15,7,20,3]

返回如下的二叉树:

3
   / \
  9  20
    /  \
   15   7

题解

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

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

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

例如:

先序为:[1, 2]

后序为:[2, 1]

可以构建如下

1
   / 
  2
1
     \
      2

这个面试官也会问的。

回到这个题目。

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

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

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

因为后序后遍历根节点,后续最后一个节点为整棵树的根节点,可以确定根节点为3;

再根据中序得到:

leftInOrder = [9]

RightInOrder = [15, 20 ,7]

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

所以,

LeftPostOrder = [9]

RightPostOrder = [15, 7, 20]

至此,划分为子问题:

leftInOrder = [9]

LeftPostOrder = [9]

构建左子树。

RightPreOrder = [20, 15, 7]

RightPostOrder = [15, 7, 20]

构建右子树。

class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return helper(inorder, postorder, postorder.length - 1, 0, inorder.length - 1);
    }

    public TreeNode helper(int[] inorder, int[] postorder, int postEnd, int inStart, int inEnd) {
        if (inStart > inEnd) {
            return null;
        }

        int currentVal = postorder[postEnd];
        TreeNode current = new TreeNode(currentVal);
        
        int inIndex = 0; 
        for (int i = inStart; i <= inEnd; i++) {
            if (inorder[i] == currentVal) {
                inIndex = i;
            }
        }
        TreeNode left = helper(inorder, postorder, postEnd - (inEnd- inIndex) - 1, inStart, inIndex - 1);
        TreeNode right = helper(inorder, postorder, postEnd - 1, inIndex + 1, inEnd);
        current.left = left;
        current.right = right;
        return current;
    }
}

热门阅读

【Leetcode】106. 从中序与后序遍历序列构造二叉树2

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


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

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

Chinese Authoritarianism in the Information Age

Chinese Authoritarianism in the Information Age

Routledge / 2018-2-13 / GBP 115.00

This book examines information and public opinion control by the authoritarian state in response to popular access to information and upgraded political communication channels among the citizens in co......一起来看看 《Chinese Authoritarianism in the Information Age》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

在线进制转换器
在线进制转换器

各进制数互转换器