Last active
July 25, 2021 11:59
-
-
Save kYroL01/15b41a3deb302558085830eaab27a737 to your computer and use it in GitHub Desktop.
Lowest Common Ancestor for a BST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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