1. 算法
1.1 根据中序遍历和后序遍历构建二叉树
先来根据例子分析,题目来源LeetCode106,从中序和后序遍历序列构造二叉树,力扣
给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
图1. 中序遍历后序遍历构造二叉树示例
分析,根据中序遍历和后序遍历发现,后序遍历序列中的最后一个节点为当前的根节点,从中序遍历中找到根节点(改题目隐含一个前提:列表中的元素是唯一的),则左侧的为左子树,右侧的为右子树。左子树和右子树按照相同的方式构建树,直到列表中只有一个节点为止,返回。整个过程如下图所示:
图2. 根据中序遍历和后序遍历构建二叉树的思路图示
算法如下,
初始化当前的根节点为postorder中的最后一个元素
(1)在inorder中找到当前根节点的索引index,
(2)若index不在inorder中的起始位置(index!=0)
则其左子树的中序遍历为inorder[0:index],后序遍历为postorder[0:index]
root的左子节点为左子树递归调用函数
(3)若index不在inorder中的末尾位置(index!=len(inorder))
其右子树的中序遍历为inorder[index+1:],后序遍历为postorder[index,-1]
root的右子节点为右子树递归调用函数
直至列表中只有一个节点为止,此时为叶子节点,返回。
1.2 构造最大二叉树
LeetCode654,最大二叉树,力扣
给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:
创建一个根节点,其值为 nums 中的最大值。
递归地在最大值 左边 的 子数组前缀上 构建左子树。
递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 nums 构建的 最大二叉树 。
图3. 最大二叉树的示例
分析,和上一道题目类似,关键在于找到根节点的左子树和右子树。在该题目中,左子树即最大值的左边;右子树即为最大值的右边。不再赘述。
2. 代码
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def set_left(self, left):
self.left = left
def set_right(self, right):
self.right = right
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if postorder == []:
return
root = TreeNode(postorder[-1])
index = inorder.index(postorder[-1])
if index != 0:
inorder_left = inorder[0: index]
postorder_left = postorder[0: index]
root.left = self.buildTree(inorder_left, postorder_left)
if index != len(inorder) - 1:
inorder_right = inorder[index+1:]
postorder_right = postorder[index:-1]
root.right = self.buildTree(inorder_right, postorder_right)
return root
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if nums == []:
return
root = TreeNode(max(nums))
index = nums.index(max(nums))
if index != 0:
root.left = self.constructMaximumBinaryTree(nums[0: index])
if index != len(nums)-1:
root.right = self.constructMaximumBinaryTree(nums[index+1:])
return root
if __name__ == '__main__':
sol = Solution()
inorder = [9, 3, 15, 20, 7]
postorder = [9, 15, 7, 20, 3]
path = sol.buildTree(inorder, postorder)
r = sol.preorderTraversal(path)
nums = [3, 2, 1, 6, 0, 5]
root = sol.constructMaximumBinaryTree(nums)
r = sol.preorderTraversal(root)
print(r)