【LeetCode每日一题】[简单]235. 二叉搜索树的最近公共祖先
235. 二叉搜索树的最近公共祖先
题目来源
算法思想:树,递归,深度优先遍历
题目:
java代码
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//二叉搜索树种,结点不相同;
TreeNode ancestor = root;
//如果p,q的值均大于root,则最近祖先在root.righ右子树上;
//如果p,q的值均小于root,则最近祖先在root.righ左子树上;
//此外,即最近祖先结点为root
while (true) {
if (p.val < ancestor.val && q.val < ancestor.val) {
ancestor = ancestor.left;
} else if (p.val > ancestor.val && q.val > ancestor.val) {
ancestor = ancestor.right;
} else {
break;
}
}
return ancestor;
}