235. Lowest Common Ancestor of a Binary Search Tree
原题链接:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
代码实现:
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
// System.out.println(s.lowestCommonAncestor());
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p == null || q == null) {
return null;
}
if (p.val > q.val) { // just make p.val <= q.val; 这一步可以单独抽出来,下面的递归逻辑单独写一个递归函数来
TreeNode temp = p;
p = q;
q = temp;
}
if (root.val >= p.val && root.val <= q.val) {
return root;
}
if (root.val > q.val) {
return lowestCommonAncestor(root.left, p, q);
}
if (root.val < p.val) {
return lowestCommonAncestor(root.right, p, q);
}
return null;
}
}