一、 654.最大二叉树
题目
思路
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
if not nums: # 终止条件
return None
# 1找到nums中的最大值,及其索引
maxval = max(nums)
max_index = nums.index(maxval)
# 2 构造二叉树
root = TreeNode(maxval)
# 3 分割左子树,右子树
left = nums[:max_index]
right = nums[max_index+1:]
# 4 构造左子树,右子树 递归
root.left = self.constructMaximumBinaryTree(left)
root.right = self.constructMaximumBinaryTree(right)
# 5 返回
return root
二、 617.合并二叉树
题目
思路
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if not root1:
return root2
if not root2:
return root1
# 把root2的值加到root1上
root1.val += root2.val
# 这里是构造了新的二叉树,所以必须有root1.left =
root1.left = self.mergeTrees(root1.left,root2.left)
root1.right = self.mergeTrees(root1.right,root2.right)
return root1
三、 700.二叉搜索树中的搜索
题目
思路
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
# if not root or root.val == val: # 终止条件 节点为空或者找到目标值
# return root
# # 根据二叉搜索树的特点,左子树的值小于根节点,右子树的值大于根节点
# if root.val > val: # 根节点大于目标值 ,则目标值可能在左子树
# return self.searchBST(root.left,val) # 这里一定要返回,避免递归还执行判断操作
# if root.val < val: # 根节点小于目标值 ,则目标值可能在右子树
# return self.searchBST(root.right,val)
# # self.searchBST(root.left,val) 不能直接递归 这样会把所有节点遍历到,导致不停return
# # self.searchBST(root.right,val)
# 迭代
while root:
if root.val > val:
root = root.left
elif root.val < val:
root = root.right
else :
return root
return None
四、98.验证二叉搜索树
题目
思路
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
re = []
def zhongxu(root:TreeNode)-> None:
if not root:
return
zhongxu(root.left)
re.append(root.val)
zhongxu(root.right)
def is_sort(x):
for i in range(1,len(x)):
if x[i-1] >= x[i]: # 这里的等号不能少
return False
return True
zhongxu(root)
bool_ = is_sort(re)
return bool_