530.二叉搜索树的最小绝对差
解法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: Optional[TreeNode]) -> int:
# method 1
res = []
min_value = inf
def dfs(root):
if not root:
return None
dfs(root.left)
res.append(root.val)
dfs(root.right)
dfs(root)
for i in range(len(res)-1):
num1 = res[i]
num2 = res[i+1]
min_value = min(min_value,abs(num1-num2))
return min_value
解法2:递归(左右指针)
# 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: Optional[TreeNode]) -> int:
# method 2
pre = None
result = inf
def dfs(cur):
if not cur:
return
nonlocal pre
nonlocal result
dfs(cur.left)
if pre != None:
result = min(result,abs(cur.val-pre.val))
pre = cur
dfs(cur.right)
dfs(root)
return result
501.二叉搜索树中的众数
解法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 findMode(self, root: Optional[TreeNode]) -> List[int]:
pre = None
count = 0
max_count = 0
res = []
def dfs(cur):
if not cur:
return None
nonlocal pre
nonlocal count
nonlocal max_count
nonlocal res
dfs(cur.left)
if pre == None:
count = 1
elif pre.val == cur.val:
count += 1
else:
count = 1
pre = cur
if count == max_count:
res.append(cur.val)
elif count > max_count:
max_count = count
res = [cur.val]
dfs(cur.right)
dfs(root)
return res
236. 二叉树的最近公共祖先
解法:递归(后序)
# 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:
return None
if root == p or root == q:
return root
left_node = self.lowestCommonAncestor(root.left,p,q)
right_node = self.lowestCommonAncestor(root.right,p,q)
if left_node and right_node:
return root
if left_node and not right_node:
return left_node
if not left_node and right_node:
return right_node
if not left_node and not right_node:
return None