二叉搜索树的最近公共祖先

二叉搜索树:左子树的值小于右子树的值(不会出现重复的情况)

/**
 * 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){
            if(root.val > p.val && root.val > q.val){
                root = root.left;
            }else if(root.val < p.val && root.val < q.val){
                root = root.right;
            }else{
                break;//找到==情况或者是>和<情况证明找到了公共祖先
            }
        }
        return root;
    }

}

posted @ 2020-07-23 18:23  浅滩浅  阅读(102)  评论(0编辑  收藏  举报