当前位置 博文首页 > Liu,:Leetcode—— 二叉搜索树的最近公共祖先
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode ancerstor = root;
while(true){
if(ancerstor.val > p.val && ancerstor.val > q.val)
ancerstor = ancerstor.left;
else if(ancerstor.val < p.val && ancerstor.val < q.val)
ancerstor = ancerstor.right;
else
break;
}
return ancerstor;
}
}
cs