1. Lowest Common Ancestor of a Binary Search Tree (Leetcode Number: 235)
The solution of 236 works here as well. The following solution is only for BST due to its feature.
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root.val < p.val and root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
if root.val > p.val and root.val > q.val:
return self.lowestCommonAncestor(root.left, p, q)
return root
2. Insert into a Binary Search Tree (Leetcode Number: 701)
Highlight the feature of BST and design the traversal strategy accordingly would save time on searching!
Write the termination condition on top of the function!
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return TreeNode(val)
if root.val < val:
root.right = self.insertIntoBST(root.right, val)
if root.val > val:
root.left = self.insertIntoBST(root.left, val)
return root
3. Delete Node in a BST (Leetcode Number: 450)
Got stuck at the while function
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if not root:
return None
if root.val < key:
root.right = self.deleteNode(root.right, key)
elif root.val > key:
root.left = self.deleteNode(root.left, key)
else:
if not root.left:
return root.right
if not root.right:
return root.left
# Replacement strategy for the nodes that have both left child and right child
node = root.right
while node.left:
node = node.left
node.left = root.left
root = root.right
return root