剑指 Offer 68 - I. 二叉搜索树的最近公共祖先

/**
 * 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) {
            while(root != null){
                //因为是二叉搜索树,p、q 值都大于 root 说明都在root右子树中
                if(p.val > root.val && q.val > root.val){
                    root = root.right;
                //p、q 值都小于 root 说明都在root左子树中
                }else if(p.val < root.val && q.val < root.val){
                    root = root.left;
                //一大一小,说明root是公共祖先,返回
                }else break;
            }
            return root;

    }
}

 

上一篇:oracle start with connect by prior 递归查询


下一篇:4.【一维数组】【入门】输出奇数和偶数