513. 找树左下角的值
class Solution:
def __init__(self):
self.max_depth = -1
self.val = 0
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
if not root:return
self.dfs(root,0)
return self.val
def dfs(self,root,cur_depth):
if not root.left and not root.right:
if cur_depth > self.max_depth:
self.max_depth = cur_depth
self.val = root.val
if root.left:
cur_depth +=1
self.dfs(root.left,cur_depth)
cur_depth -=1
if root.right:
cur_depth +=1
self.dfs(root.right,cur_depth)
cur_depth -=1
112. 路径总和
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
def isornot(root,targetSum):
if not root.left and not root.right and targetSum==0:
return True
if not root.left and not root.right:
return False
if root.left:
targetSum -= root.left.val
if isornot(root.left,targetSum): return True
targetSum += root.left.val
if root.right:
targetSum -= root.right.val
if isornot(root.right,targetSum): return True
targetSum -= root.right.val
return False
return isornot(root,targetSum-root.val) if root else False
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not postorder:return
root_val = postorder[-1]
root = TreeNode(root_val)
index = inorder.index(root_val)
inorder_left = inorder[:index]
inorder_right = inorder[index+1:]
postorder_left = postorder[:len(inorder_left)]
postorder_right = postorder[len(inorder_left):-1]
root.left = self.buildTree(inorder_left,postorder_left)
root.right = self.buildTree(inorder_right,postorder_right)
return root
654. 最大二叉树
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
if not nums:return
root_val_index = nums.index(max(nums))
root_val = nums[root_val_index]
root = TreeNode(root_val)
left = nums[:root_val_index]
right = nums[root_val_index+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 and not root2:
return
if not root2:
return root1
if not root1:
return root2
val = root1.val + root2.val
root = TreeNode(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]:
ans = [None]
if not root:return
def dfs(root):
if not root:return
if root.val == val:
ans[0] = root
return
if root.val < val:
dfs(root.right)
if root.val > val:
dfs(root.left)
dfs(root)
return ans[0]
98. 验证二叉搜索树
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
res = []
def helper(root):
if not root:
return
helper(root.left)
res.append(root.val)
helper(root.right)
helper(root)
return res == sorted(res) and len(set(res)) == len(res)
530. 二叉搜索树的最小绝对差
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
path = []
def dfs(root,path):
if root.left:
dfs(root.left,path)
path.append(root.val)
if root.right:
dfs(root.right,path)
return path
res = dfs(root,path)
cost = 10**6
for i in range(1,len(res)):
cost = min(res[i] - res[i-1],cost)
return cost
501. 二叉搜索树中的众数
class Solution:
def findMode(self, root: Optional[TreeNode]) -> List[int]:
path = {}
def dfs(root,path):
if root.left:
dfs(root.left,path)
path[root.val] = path.get(root.val,0) +1
if root.right:
dfs(root.right,path)
return path
res = dfs(root,path)
mode = max(res.values())
return [key for key in res.keys() if res[key] ==mode]
236. 二叉树的最近公共祖先
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root: return None
if root ==p or root ==q:return root
left = self.lowestCommonAncestor(root.left ,p,q)
right = self.lowestCommonAncestor(root.right,p,q)
if left and right:return root
if left and not right:return left
if right and not left:return right
else:
return
235. 二叉搜索树的最近公共祖先
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def dfs(cur,p,q):
if not cur:return
if cur.val > p.val and cur.val > q.val:
left = dfs(cur.left,p,q)
if left:return left
if cur.val < p.val and cur.val < q.val:
right = dfs(cur.right,p,q)
if right:return right
return cur
return dfs(root,p,q)
701. 二叉搜索树中的插入操作
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
newNode = TreeNode(val)
if not root: return newNode
if not root.left and val < root.val:
root.left = newNode
if not root.right and val > root.val:
root.right = newNode
if val < root.val:
self.insertIntoBST(root.left, val)
if val > root.val:
self.insertIntoBST(root.right, val)
return root
450. 删除二叉搜索树中的节点
class Solution:
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
if not root: return root #第一种情况:没找到删除的节点,遍历到空节点直接返回了
if root.val == key:
if not root.left and not root.right: #第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点
return None
if not root.left and root.right: #第三种情况:其左孩子为空,右孩子不为空,删除节点,右孩子补位 ,返回右孩子为根节点
root = root.right
return root
if root.left and not root.right: #第四种情况:其右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
root = root.left
return root
else: #第五种情况:左右孩子节点都不为空,则将删除节点的左子树放到删除节点的右子树的最左面节点的左孩子的位置
v = root.right
while v.left:
v = v.left
v.left = root.left
root = root.right
return root
if root.val > key: root.left = self.deleteNode(root.left,key) #左递归
if root.val < key: root.right = self.deleteNode(root.right,key) #右递归
return root
669. 修剪二叉搜索树
class Solution:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if not root: return None
if root.val < low:
# 若当前root节点小于左界:只考虑其右子树,用于替代更新后的其本身,抛弃其左子树整体
return self.trimBST(root.right, low, high)
if high < root.val:
# 若当前root节点大于右界:只考虑其左子树,用于替代更新后的其本身,抛弃其右子树整体
return self.trimBST(root.left, low, high)
if low <= root.val <= high:
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root
108. 将有序数组转换为二叉搜索树
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
root = self.dfs(0,len(nums)-1,nums)
return root
def dfs(self,left,right,nums):
if left > right:return
mid = left + (right-left)//2
mid_root = TreeNode(nums[mid])
mid_root.left = self.dfs(left,mid-1,nums)
mid_root.right = self.dfs(mid+1,right,nums)
return mid_root
538. 把二叉搜索树转换为累加树
class Solution:
def __init__(self):
self.pre = TreeNode()
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
self.traversal(root)
return root
def traversal(self, root: TreeNode) -> None:
# 因为要遍历整棵树,所以递归函数不需要返回值
if not root:
return None
# 单层递归逻辑:中序遍历的反译 - 右中左
self.traversal(root.right) # 右
# 中节点:用当前root的值加上pre的值
root.val += self.pre.val # 中
self.pre = root
self.traversal(root.left) # 左