1. Minimum Absolute Difference in BST (Leetcode Number: 530)
BST (Binary search tree), also called an ordered or sorted binary tree, is a rooted binary tree data structure with the key of each internal node being greater than all the keys in the respective node's left subtree and less than the ones in its right subtree.
In this case, the DFS Inorder strategy is deployed here.
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
dep_list = []
dep_dif = float("inf")
def recur_list(root):
if root is None:
return None
# Left -> Node -> Right
if root.left:
recur_list(root.left)
dep_list.append(root.val)
if root.right:
recur_list(root.right)
return dep_list
recur_list(root)
for i in range(len(dep_list) - 1):
dep_dif = min(abs(dep_list[i] - dep_list[i + 1]), dep_dif)
return dep_dif
2. Find Mode in Binary Search Tree (Leetcode Number: 501)
Inorder DFS strategy
class Solution:
def findMode(self, root: Optional[TreeNode]) -> List[int]:
stack = []
res = []
pre = None
cur = root
maxCount, count = 0, 0
#if not root:
# return None
# Stack should be created in the loop
# stack.append(root)
while cur or stack:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
if pre == None:
count = 1
elif pre.val == cur.val:
count += 1
else:
count =1
if count == maxCount:
res.append(cur.val)
if count > maxCount:
maxCount = count
res.clear()
res.append(cur.val)
pre = cur
cur = cur.right
return res
3. Lowest Common Ancestor of a Binary Tree (Leetcode Number: 236)
The postorder DFS strategy will guarantee the orders of searching and all nodes would be checked. The return value of any node that doesn't contain p or q is null.
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root or p == root or q == root:
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
return right