# 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 maxDepth(self, root: TreeNode) -> int:
if not root: return 0
l = self.maxDepth(root.left)
r = self.maxDepth(root.right)
return (max(l,r)+1)
# 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 minDepth(self, root: TreeNode) -> int:
if not root: return 0
if root.left and not root.right: return self.minDepth(root.left) + 1
if root.right and not root.left: return self.minDepth(root.right) + 1
return (min(self.minDepth(root.left),self.minDepth(root.right))+1)
# 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 getMinimumDifference(self, root: TreeNode) -> int:
self.res = float('inf')
self.pre = float('-inf')
def dfs(root):
if not root: return
dfs(root.left)
self.res = min(self.res, root.val - self.pre)
self.pre = root.val
dfs(root.right)
dfs(root)
return self.res
# 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 diameterOfBinaryTree(self, root: TreeNode) -> int:
self.res=0
def maxDepth(root: TreeNode) -> int:
if not root: return 0
l = maxDepth(root.left)
r = maxDepth(root.right)
self.res = max(self.res, l+r)
return (max(l,r)+1)
maxDepth(root)
return self.res
# 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 widthOfBinaryTree(self, root: TreeNode) -> int:
res = 0
# 初始化序列,其中一个存节点,一个存储索引位置
q =[[root,0]]
while q:
#初始化该层最左边和右边不为空的节点索引
left = float('inf'); right = 0
#开始进行层级遍历
for i in range(len(q)):
node = q.pop(0)
#如果节点不为空节点,更新下一个层级的节点,并更新最左侧索引和最右侧索引
if node[0]:
q.append([node[0].left,node[1]*2])
q.append([node[0].right,node[1]*2+1])
left = min([left,node[1]])
right = max([right,node[1]])
#判断该层级是否有效
if left <= right:
res = max([res,right-left+1])
return res
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> bool:
if not root: return 0
l = self.maxDepth(root.left)
r = self.maxDepth(root.right)
return (max(l,r)+1)
def isBalanced(self, root: TreeNode) -> bool:
if not root: return True
return abs(self.maxDepth(root.left)-self.maxDepth(root.right)) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)
# 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 invertTree(self, root: TreeNode) -> TreeNode:
if not root or not root.left and not root.right:
return root
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
# 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 isMirror(self, m: TreeNode, n: TreeNode) -> bool:
if not m and not n: return True
if m and n and m.val == n.val:
return self.isMirror(m.left,n.right) and self.isMirror(m.right,n.left)
return False
def isSymmetric(self, root: TreeNode) -> bool:
return self.isMirror(root,root)
# 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: TreeNode, root2: TreeNode) -> TreeNode:
if not root1: return root2
if not root2: return root1
root = TreeNode(0)
root.val = root1.val + root2.val
root.left = self.mergeTrees(root1.left,root2.left)
root.right = self.mergeTrees(root1.right,root2.right)
return root
剑指 Offer 68 - II. 二叉树的最近公共祖先
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root or root.val == p.val or root.val == q.val: return root
l = self.lowestCommonAncestor(root.left, p, q)
r = self.lowestCommonAncestor(root.right, p, q)
if not l: return r
if not r: return l
return root
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left,p,q)
if p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right,p,q)
return root
# 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 helper(self, root: TreeNode, lower, upper) -> bool:
if not root: return True
if root.val <= lower or root.val >= upper:
return False
return self.helper(root.left, lower, root.val) and self.helper(root.right, root.val, upper)
def isValidBST(self, root: TreeNode) -> bool:
return self.helper(root, float('-inf'), float('inf'))
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
#先尝试中序遍历保存所有节点,再找倒数第k个节点
def inOrder(root):
if not root: return
inOrder(root.left)
self.inorder.append(root.val)
inOrder(root.right)
self.inorder = []
inOrder(root)
return self.inorder[-k]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if not nums: return
p = len(nums) // 2
root = TreeNode(nums[p])
root.left = self.sortedArrayToBST(nums[:p])
root.right = self.sortedArrayToBST(nums[p+1:])
return root
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# 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 sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
if not head: return
if not head.next: return TreeNode(head.val)
pre, fast, slow = None, head, head
while fast and fast.next:
pre = slow
fast = fast.next.next
slow = slow.next
root = TreeNode(slow.val)
# pre记录slow的前一个结点,链表需要断开操作
pre.next = None
root.left = self.sortedListToBST(head)
root.right = self.sortedListToBST(slow.next)
return root
# 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 increasingBST(self, root: TreeNode) -> TreeNode:
self.head = self.cur = TreeNode(None)
def dfs(root):
if not root: return
dfs(root.left)
root.left = None
self.cur.right = root
self.cur = root
dfs(root.right)
dfs(root)
return self.head.right
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def convertBiNode(self, root: TreeNode) -> TreeNode:
self.head = self.cur = TreeNode(None)
def dfs(root):
if not root: return
dfs(root.left)
root.left = None
self.cur.right = root
self.cur = root
dfs(root.right)
dfs(root)
return self.head.right
# 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 balanceBST(self, root: TreeNode) -> TreeNode:
# 先中序遍历
def inorder(root):
if root.left: inorder(root.left)
res.append(root.val)
if root.right: inorder(root.right)
# 再构造平衡树
def build(l, r):
mid = (l + r) // 2
root = TreeNode(res[mid])
if l < mid:
root.left = build(l, mid - 1)
if r > mid:
root.right = build(mid + 1, r)
return root
res = list()
inorder(root)
return build(0, len(res) - 1)
# 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 flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root: return
self.flatten(root.left)
self.flatten(root.right)
tmp = root.right
root.right = root.left
root.left = None
while root.right: root = root.right;
root.right = tmp
# 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 flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
self.last = None
def flat(root):
if not root: return None
flat(root.right)
flat(root.left)
root.right = self.last
self.last = root
root.left = None
flat(root)
"""
# Definition for a Node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
"""
class Solution:
def dfs(self, root: 'Node') -> 'Node':
if not root: return
self.dfs(root.left)
# 双向链表
root.left = self.pre
self.pre.right = root
# 右移指针
self.pre = root
self.dfs(root.right)
def treeToDoublyList(self, root: 'Node') -> 'Node':
if not root: return
self.pre = head = Node()
self.dfs(root)
# 首尾相连
self.pre.right, head.right.left = head.right, self.pre
return head.right
# 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 leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
l1, l2 = [], []
def dfs(root, ll):
if not root.left and not root.right: ll.append(root.val)
if root.left: dfs(root.left, ll)
if root.right: dfs(root.right, ll)
return ll
s1 = dfs(root1, l1)
s2 = dfs(root2, l2)
return s1 == s2
# 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 isCousins(self, root: TreeNode, x: int, y: int) -> bool:
x_depth, x_parent, y_depth, y_parent = None, None, None, None
# 标准dfs模板, 只是在中间加了一些判断逻辑
def dfs(root, parent, x, y, depth):
nonlocal x_depth, x_parent, y_depth, y_parent
if root is None:
return
# 判断 x, y 是否等于当前节点的值, 是的话更新 x 或者 y 的深度和parent
if root.val == x:
x_depth = depth
x_parent = parent
if root.val == y:
y_depth = depth
y_parent = parent
dfs(root.left, root, x, y, depth+1)
dfs(root.right, root, x, y, depth+1)
dfs(root, None, x, y, 0)
# 最后保证 x, y的深度一样, 但是parent节点不一样, 这样才是堂兄弟
return x_depth == y_depth and x_parent != y_parent
剑指 Offer II 056. 二叉搜索树中两个节点之和
# 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 findTarget(self, root: TreeNode, k: int) -> bool:
def dfs(root):
if not root: return
dfs(root.left)
nums.append(root.val)
dfs(root.right)
nums = list()
dfs(root)
left = 0; right = len(nums) - 1
while left < right:
s = nums[left] + nums[right]
if s == k: return True
if s < k: left += 1
if s > k: right -= 1
return False
剑指 Offer II 059. 数据流的第 K 大数值
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.q = nums
heapq.heapify(self.q)
def add(self, val: int) -> int:
heapq.heappush(self.q, val)
while len(self.q) > self.k:
heapq.heappop(self.q)
return self.q[0]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)