Dynamic Programming Dynamic Programming Graph

Lowest Common Ancestor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
     if root == nil || root == p || root == q {
         return root 
     }
     left := lowestCommonAncestor(root.Left,p,q)
     right := lowestCommonAncestor(root.Right,p,q)
     if left != nil && right != nil {
         return root 
     }
     if left != nil{
         return left 
     } else{
         return right 
     }
}

🎰