码迷,mamicode.com
首页 > 其他好文 > 详细

235. Lowest Common Ancestor of a Binary Search Tree

时间:2018-03-25 18:07:05      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:递归函数   链接   com   turn   make   https   span   desc   mon   

原题链接: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

标签:递归函数   链接   com   turn   make   https   span   desc   mon   

原文地址:https://www.cnblogs.com/optor/p/8645357.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!