class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
if not nums:
return None
max_num = max(nums)
max_idx = nums.index(max_num)
root = TreeNode(max_num)
l_nums = nums[:max_idx]
r_nums = nums[max_idx + 1:]
root.left = self.constructMaximumBinaryTree(l_nums)
root.right = self.constructMaximumBinaryTree(r_nums)
return root
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if not root1 and not root2:
return None
if not root1:
root1 = TreeNode(0)
if not root2:
root2 = TreeNode(0)
root = TreeNode(root1.val + root2.val)
root.left = self.mergeTrees(root1.left, root2.left)
root.right = self.mergeTrees(root1.right, root2.right)
return root
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return None
if root.val == val:
return root
elif val < root.val:
return self.searchBST(root.left, val)
else:
return self.searchBST(root.right, val)
我一开始都搜索了,但是因为它是二叉搜索树,所以可以看大小减少搜索量。
98. 验证二叉搜索树
# 递归,中序遍历,正好是依次取的,转为数组
class Solution:
def traversal(self, node, idx):
if node is None:
return
self.traversal(node.left, idx)
idx.append(node.val)
self.traversal(node.right, idx)
def isValidBST(self, root: Optional[TreeNode]) -> bool:
idx = []
self.traversal(root, idx)
for i in range(len(idx) - 1):
if idx[i + 1] - idx[i] <= 0:
return False
return True
# 递归,中序遍历,每取一个,就看一个
class Solution:
def __init__(self):
self.maxVal = float('-inf')
def isValidBST(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
left = self.isValidBST(root.left)
if self.maxVal < root.val:
self.maxVal = root.val
else:
return False
right = self.isValidBST(root.right)
return left and right
中序遍历转为数组确实没有想到,挺有趣的。下面的第二个其实不太能理解。