随笔分类 - 算法 / 树
摘要:669. 修剪二叉搜索树 树的修剪方式赋值。 1、递归法 class Solution: def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: if root is None:
阅读全文
摘要:235. 二叉搜索树的最近公共祖先 关键点:最近公共祖先的判断,二叉树的特性 1、做二叉树的模式 class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'Tr
阅读全文
摘要:二叉搜素树,利用中序遍历的升序结果 530.二叉搜索树的最小绝对差 1、递归中序遍历 class Solution: def __init__(self): self.pre = None self.res = float('inf') def getMinimumDifference(self,
阅读全文
摘要:654.最大二叉树 1、使用切片 class Solution: def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]: if len(nums) == 0: return None max_val =
阅读全文
摘要:513.找树左下角的值 1、层序遍历迭代法 def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: queue = [root] res = float('-inf') while queue: n = len(queue) f
阅读全文
摘要:110.平衡二叉树 1、递归法 class Solution: def isBalanced(self, root: Optional[TreeNode]) -> bool: if self.get_height(root) != -1: # -1 代表高度差大于 1 return True els
阅读全文
摘要:104.二叉树的最大深度 1、后续遍历递归法 class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if root is None: return 0 left_depth = self.maxDepth(root.
阅读全文
摘要:前序遍历 统一写法用None 来区分遍历查找的节点和处理节点 1、递归法 class Solution: def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: res = [] self.preorder(root,
阅读全文
摘要:层序遍历 1、迭代法,使用队列 class Solution: def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: res = [] if root is None: return res queue = [root]
阅读全文