654. 最大二叉树
- 很典型的递归
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
if len(nums) == 0:
return
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
617. 合并二叉树
- 自己写还是递归
- 题解里没有新建root,而是利用了root1 : root1.val += root2.val
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if not root1 and not root2:
return
if not root1:
return root2
if not root2:
return root1
root = TreeNode(root1.val + root2.val)
root.left = self.mergeTrees(root1.left, root2.left)
root.right = self.mergeTrees(root1.right, root2.right)
return root
700. 二叉搜索树中的搜索
- 定义题?哦我写的是迭代,其实递归也可以
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
cur = root
while(cur):
if cur.val == val:
return cur
elif cur.val > val:
cur = cur.left
else: cur = cur.right
return
98. 验证二叉搜索树
- 二叉树练完感觉自己只会写递归了…
- 哦!中序就是二叉搜索树的顺序,只要中序遍历再判断是不是递增就好了
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
return self.traversal(root, -float('inf'), float('inf'))
def traversal(self, root, min_val, max_val):
if not root:
return True
if root.val <= min_val or root.val >= max_val:
return False
if not root.left and not root.right:
return True
left = self.traversal(root.left, min_val, root.val)
right = self.traversal(root.right, root.val, max_val)
return left and right