Skip to content

Instantly share code, notes, and snippets.

@fever324
Created July 21, 2015 09:12
Show Gist options
  • Select an option

  • Save fever324/0abf6a404a617782f980 to your computer and use it in GitHub Desktop.

Select an option

Save fever324/0abf6a404a617782f980 to your computer and use it in GitHub Desktop.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if ((root.val >= p.val && root.val <= q.val) || (root.val <= p.val && root.val >= q.val)) {
return root;
} else {
if (root.val > p.val) {
return lowestCommonAncestor(root.left, p, q);
} else {
return lowestCommonAncestor(root.right, p ,q);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment