Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 12, 2017 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/e7121800609be69004b6a9419b937efa to your computer and use it in GitHub Desktop.
Save InterviewBytes/e7121800609be69004b6a9419b937efa to your computer and use it in GitHub Desktop.
LCA BST
package com.interviewbytes.trees;
public class LowestCommonAncestorBST {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p == root || q == root) return root;
if ((p.val < root.val && q.val > root.val) || (q.val < root.val && p.val > root.val)) return root;
if (p.val < root.val && q.val < root.val) return lowestCommonAncestor(root.left, p, q);
return lowestCommonAncestor(root.right, p, q); //if(p.val > root.val && q.val > root.val)
}
}
package com.interviewbytes.trees;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment