比之前利用中序和后序构建二叉树简单一些
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
if not nums:
return None
max_val = max(nums)
max_index = nums.index(max_val)
root = TreeNode(max_val)
root.left = self.constructMaximumBinaryTree(nums[:max_index])
root.right = self.constructMaximumBinaryTree(nums[max_index+1:])
return root
递归法,直接利用root1
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if not root1:
return root2
if not root2:
return root1
root1.val += root2.val
root1.left = self.mergeTrees(root1.left, root2.left)
root1.right = self.mergeTrees(root1.right, root2.right)
return root1
递归法
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)
else:
return self.searchBST(root.right, val)
迭代法
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
while root:
if root.val == val:
return root
elif root.val > val:
root = root.left
else:
root = root.right
return
递归法
递归三部曲
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
return self.traversal(root, float('-inf'), float('inf'))
def traversal(self, node, min_val, max_val):
if not node:
return True
if node.val <= min_val or node.val >= max_val:
return False
return self.traversal(node.left, min_val, min(max_val, node.val)) and self.traversal(node.right, max(min_val, node.val), max_val)
看了题解之后,和我写的好不一样,需要花时间研究一下,看了视频
直接的做法:中序遍历得到数组,看看数组是不是递增
优化的做法:在中序遍历的时候,直接比较遍历值是不是递增的。
在这种做法的时候,可以先声明一个最小值,但是有可能树中存在这个最小值导致结果报错,优化的做法是将遍历的第一个元素赋值给声明的元素,然后逐渐比较
class Solution:
def __init__(self):
self.min_val = float('-inf')
def isValidBST(self, root: Optional[TreeNode]) -> bool:
# 中序遍历,查看是否递增
if not root:
return True
if not self.isValidBST(root.left):
return False
if root.val <= self.min_val:
return False
else:
self.min_val = root.val
if not self.isValidBST(root.right):
return False
return True
写的不够简洁,重新优化一次
class Solution:
def __init__(self):
self.max_val = float('-inf')
def isValidBST(self, root: Optional[TreeNode]) -> bool:
# 中序遍历,查看是否递增
if not root:
return True
left = self.isValidBST(root.left)
if root.val <= self.max_val:
return False
else:
self.max_val = root.val
right = self.isValidBST(root.right)
return left and right
不使用最小值的办法优化一次
class Solution:
def __init__(self):
self.pre = None
def isValidBST(self, root: Optional[TreeNode]) -> bool:
# 中序遍历,查看是否递增
if not root:
return True
left = self.isValidBST(root.left)
if self.pre and root.val <= self.pre.val:
return False
else:
self.pre = root
right = self.isValidBST(root.right)
return left and right