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

题目来源:

https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

题目描述:

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

代码如下:

/**
 * 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) {
        if(root==null)return null;  
        // 要么在左子树,要么在右子树,要么就是根节点
        while(root != null){  
            if(p.val>root.val&&q.val>root.val)  
                root=root.right;  
            else if(p.val<root.val&&q.val<root.val)  
                root=root.left;  
            else return root;  
        }
        return root;
    }
}