文章目录
530. Minimum Absolute Difference in BST
class Solution:
def __init__(self):
self.pre = None
self.res = float('inf')
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
def inorder(root):
if not root:
return
inorder(root.left)
if self.pre != None:
self.res = min(self.res, root.val - self.pre)
self.pre = root.val
inorder(root.right)
inorder(root)
return self.res
- two pointers
- Sol2: use list, 略
501. Find Mode in Binary Search Tree
Given the
root
of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.
Sol1: use hash table
class Solution1:
def findMode(self, root: Optional[TreeNode]) -> List[int]:
count_dict = {}
res = []
def inorder(root):
if not root:
return
inorder(root.left)
count_dict[root.val]=count_dict.get(root.val,0)+1
inorder(root.right)
inorder(root)
max_v = max(count_dict.values())
for x in count_dict.keys():
if count_dict[x] == max_v:
res.append(x)
return res
Sol2: two pointers
class Solution:
#only appears in nearby nodes
def __init__(self):
self.pre_value = None
self.res = []
self.count = 0
self.max_count = 0
def findMode(self, root: Optional[TreeNode]) -> List[int]:
def inorder(root):
if not root:
return
inorder(root.left)
if self.pre_value == None:
self.count = 1
elif self.pre_value == root.val:
self.count+=1
else:
self.count = 1
self.pre_value = root.val
#print(count, max_count)
if self.count== self.max_count:
self.res.append(root.val)
if self.count > self.max_count:
self.res = [root.val]
self.max_count = self.count
inorder(root.right)
inorder(root)
return self.res
236. Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes
p
andq
as the lowest node inT
that has bothp
andq
as descendants (where we allow a node to be a descendant of itself).”
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
elif left and not right:
return left
elif not left and right:
return right
else:
return None