654.最大二叉树
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
if not nums:
return None
maxvalue= max(nums)
idx = nums.index(maxvalue)
root = TreeNode(maxvalue)
left = nums[:idx]
right=nums[idx+1:]
root.left = self.constructMaximumBinaryTree(left)
root.right = self.constructMaximumBinaryTree(right)
return root
617.合并二叉树
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
700.二叉搜索树中的搜索
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
while root is not None:
if val < root.val:
root = root.left
elif val > root.val:
root = root.right
else:
return root
return None
98.验证二叉搜索树
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
stack = []
cur = root
pre = None
while cur or stack:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
if pre and cur.val <= pre.val:
return False
pre = cur
cur = cur.right
return True