题解 | #二叉搜索树的最近公共祖先#浓缩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);
    }
}
全部评论

相关推荐

爱吃肉的伊登在写日记:好棒,27届简历能做成这个样子,但是第一个项目感觉cover住难度还是不小的,特别是二面的时候肯定要对分布式系统设计这一块儿有高出正常面试者的水平才行
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务