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