leetcode654.最大二叉树
题目链接:654. 最大二叉树 - 力扣(LeetCode)
思路:构造二叉树类问题都选择前序遍历,先确定中间的节点在确定左右子树的节点。递归结束条件就是数组全部遍历完,单层递归逻辑是先找到最大值以及最大值下标,然后再用切片的方法向左向右递归最后返回。
# 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]:
if not nums:
return None
max_val = max(nums)
max_index = nums.index(max_val)
node = TreeNode(max_val)
node.left = self.constructMaximumBinaryTree(nums[:max_index])
node.right = self.constructMaximumBinaryTree(nums[max_index+1:])
return node
leetcode617.合并二叉树
题目链接:617. 合并二叉树 - 力扣(LeetCode)
思路:使用前序遍历最好理解,递归终止条件是如果t1是空就返回t2,反之返回t1,单层递归中为了节省空间,直接更改t1的结构,不重新定义二叉树,t1.val += t2.val,然后分别递归左右子树。
# 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
leetcode700.二叉搜索树中的搜索
题目链接:700. Search in a Binary Search Tree - 力扣(LeetCode)
思路:搜索树不涉及前中后序,递归终止条件是root为空或root的值为目标值,此时返回root,单层递归逻辑是如果目标值小于节点值就向左递归,如果目标值大于节点值就向右递归,同时因为本题有返回值,所以需要定义一个result来存储返回值。
# 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 root is None or root.val == val:
return root
result = None
if val < root.val:
result = self.searchBST(root.left, val)
if val > root.val:
result = self.searchBST(root.right, val)
return result
leetcode98.验证二叉搜索树
题目链接:98. 验证二叉搜索树 - 力扣(LeetCode)