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]:
max_val=0
for i in range(len(nums)):
max_val=max(max_val,nums[i])
if not nums:
return
root=TreeNode(max_val)
index=nums.index(max_val)
root.left=self.constructMaximumBinaryTree(nums[:index])
root.right=self.constructMaximumBinaryTree(nums[index+1:])
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 root1 is None:
return root2
if root2 is None:
return root1
root1.val+=root2.val
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)
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 __init__(self):
self.max_value=float('-inf')
def isValidBST(self, root: Optional[TreeNode]) -> bool:
if root is None:
return True
left=self.isValidBST(root.left)
if root.val > self.max_value:
self.max_value=root.val
else:
return False
right=self.isValidBST(root.right)
return left and right #只有当左子树和右子树都是二叉搜索树返回True