博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode106. Construct Binary Tree from Inorder and Postorder Traversal (思路及python解法)
阅读量:2242 次
发布时间:2019-05-09

本文共 767 字,大约阅读时间需要 2 分钟。

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.

For example, given

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

Return the following binary tree:

3   / \  9  20    /  \   15   7

根据中序遍历和后序遍历生成二叉树。

用递归方法很容易完成,先利用后序遍历找到根节点,然后再根据中序遍历分根节点的左子树和右子树。

需要注意的是和前序+中序有所不同,后序+中序要先写root.right,而前者要先写root.left。

class Solution:    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:        if inorder:            node = postorder.pop()            index = inorder.index(node)            root = TreeNode(node)            root.right = self.buildTree(inorder[index+1:], postorder)            root.left = self.buildTree(inorder[:index], postorder)            return root

 

转载地址:http://adrbb.baihongyu.com/

你可能感兴趣的文章
win10安装软件 打开时报错 找不到 msvcp120.dll
查看>>
PHPunit+Xdebug代码覆盖率以及遇到的问题汇总
查看>>
PHPUnit安装及使用
查看>>
PHP项目用xhprof性能分析(安装及应用实例)
查看>>
composer安装YII
查看>>
Sublime text3快捷键演示
查看>>
sublime text3 快捷键修改
查看>>
关于PHP几点建议
查看>>
硬盘的接口、协议
查看>>
VLAN与子网划分区别
查看>>
Cisco Packet Tracer教程
查看>>
02. 交换机的基本配置和管理
查看>>
03. 交换机的Telnet远程登陆配置
查看>>
微信小程序-调用-腾讯视频-解决方案
查看>>
phpStudy安装yaf扩展
查看>>
密码 加密 加盐 常用操作记录
查看>>
TP 分页后,调用指定页。
查看>>
Oracle数据库中的(+)连接
查看>>
java-oracle中几十个实用的PL/SQL
查看>>
PLSQL常用方法汇总
查看>>