构造二叉树
106. 从中序与后序遍历序列构造二叉树
题目链接:106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)
题目思路:
- 如果后续数组为空,返回空节点。
- 通过后序的最后一个元素确定二叉树的根节点。
- 根据根节点切割中序数组:左中序,右中序。
- 根据左中序的长度,切割后序数组:左后序,右后序。
- 递归得到根节点的左子树:将左中序和左后序放入函数中递归。
- 递归得到根节点的右子树:将右中序和右后续放入函数中递归。
- 返回根节点。
自己跟这个思路动手画一下,思路变清晰了,感觉比上次的递归好理解。
class Solution(object):
def buildTree(self, inorder, postorder):
# inorder: 中序,左中右
# postorder: 后序:左右中\
# 1. 检查后序数组是否为空。
if not postorder:
return None
# 2. 寻找根节点
rootVal = postorder[-1]
root = TreeNode(rootVal)
# 3. 分割中序数组
separateIndex = inorder.index(rootVal)
inLeft = inorder[:separateIndex]
inRight = inorder[separateIndex+1:]
# 4. 分割后序数组
postLeft = postorder[:len(inLeft)]
postRight = postorder[len(inLeft):len(postorder) - 1]
# 5. 递归得到左子树
root.left = self.buildTree(inLeft, postLeft)
# 6. 递归得到右子树
root.right = self.buildTree(inRight, postRight)
# 7. 返回结果!
return root
105. 从前序和中序遍历序列构造二叉树
题目链接:105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)
class Solution(object):
def buildTree(self, preorder, inorder):
# preorder: 前序,中左右
# inorder: 中序, 左中右
if not inorder:
return None
# 建立根节点
rootVal = preorder[0]
root = TreeNode(rootVal)
# 切割中序数组
separateIndex = inorder.index(rootVal)
inLeft = inorder[:separateIndex]
inRight = inorder[separateIndex+1:]
# 切割前序数组
preLeft = preorder[1:len(inLeft) + 1]
preRight = preorder[len(inLeft) + 1:len(preorder)]
# 递归得到左子树
root.left = self.buildTree(preLeft, inLeft)
# 递归得到右子树
root.right = self.buildTree(preRight, inRight)
return root
654. 最大二叉树
题目链接:654. 最大二叉树 - 力扣(LeetCode)
练习了上面两道,这道就比较容易做出来。找到数组中最大的元素和,设为root,根据其对应的下标将数组分为左子树和右子树,分别放入递归即可。
class Solution(object):
def constructMaximumBinaryTree(self, nums):
if not nums:
return None
root_val = max(nums)
root = TreeNode(root_val)
root_index = nums.index(root_val)
left = nums[:root_index]
'''if left == []:
left = None'''
right = nums[root_index + 1: len(nums)]
'''if right == []:
right = None'''
root.left = self.constructMaximumBinaryTree(left)
root.right = self.constructMaximumBinaryTree(right)
return root