题解 | #二叉搜索树的最近公共祖先#浓缩4行!

二叉搜索树的最近公共祖先

http://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f

浓缩4行!

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param p int整型 
     * @param q int整型 
     * @return int整型
     */
    public int lowestCommonAncestor (TreeNode root, int p, int q) {
        // write code here
        if (root == null) return 0; // 可以删掉, 题目说root不为空, 所以必有解
        if (root.val > Math.max(p, q)) return lowestCommonAncestor(root.left, p, q);
        if (root.val < Math.min(p, q)) return lowestCommonAncestor(root.right, p, q);
        return root.val;
    }
}

最速

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param p int整型 
     * @param q int整型 
     * @return int整型
     */
    int p, q;
    int dfs(TreeNode node) {
        if (node.val <= q && node.val >= p) return node.val;
        if (node.val > p) return dfs(node.left);
        return dfs(node.right);
    }
    public int lowestCommonAncestor (TreeNode root, int p, int q) {
        // write code here
        this.p = Math.min(p, q);
        this.q = Math.max(p, q);
        return dfs(root);
    }
}
全部评论

相关推荐

04-28 19:31
门头沟学院 Java
真烦好烦真烦:可恶的二手车贩子,居然对我们门头沟学院的人这么没礼貌
点赞 评论 收藏
分享
03-30 21:02
已编辑
武汉大学 Java
ALEX_BLX:虽然说聊天记录不可信,不过这个趋势确实如此但我觉得也要想到一点就是卷后端的人里真正有“料”的人又有多少,我说的这个料都不是说一定要到大佬那种级别,而是就一个正常的水平。即使是现在也有很多人是跟风转码的,2-3个月速成后端技术栈的人数不胜数,但今时不同往日没可能靠速成进大厂了。这种情况就跟考研一样,你能上考场就已经打败一半的人了
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务