Skip to content

Instantly share code, notes, and snippets.

@kYroL01
Last active July 25, 2021 11:59
Show Gist options
  • Save kYroL01/15b41a3deb302558085830eaab27a737 to your computer and use it in GitHub Desktop.
Save kYroL01/15b41a3deb302558085830eaab27a737 to your computer and use it in GitHub Desktop.
Lowest Common Ancestor for a BST
/**
Algorithm
- Start traversing the tree from the root node.
- If both p and q are < root, then continue to left subtree and starting step 1.
- If both p and q are > root, then continue to right subtree and starting step 1.
- If both step 2 and step 3 are not true, we have found the LCA for p and q, and we return it
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if(p.Val < root.Val && q.Val < root.Val) {
return lowestCommonAncestor(root.Left, p, q)
}
if(p.Val > root.Val && q.Val > root.Val) {
return lowestCommonAncestor(root.Right, p, q)
}
return root
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment