剑指 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;

    }
}

 

posted @ 2020-12-18 11:29  peanut_zh  阅读(51)  评论(0编辑  收藏  举报