235. Lowest Common Ancestor of a Binary Search Tree

Posted optor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
}

以上是关于235. Lowest Common Ancestor of a Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

LC.235.Lowest Common Ancestor of a Binary Search Tree

LeetCode 236. Lowest Common Ancestor of a Binary Tree; 235. Lowest Common Ancestor of a Binary Searc

#Leetcode# 235. Lowest Common Ancestor of a Binary Search Tree

235. Lowest Common Ancestor of a Binary Search Tree

235. Lowest Common Ancestor of a Binary Search Tree

235. Lowest Common Ancestor of a Binary Search Tree