235. 二叉搜索树的最近公共祖先
深度优先搜索
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        /**
         * 如果根节点值大于两者,说明在根节点的左子树,小于则说明在右子树
         * 在中间则说明根节点就是公共祖先
         */
        if (root.val > q.val && root.val > p.val){
            return lowestCommonAncestor(root.left, p, q);
        }
        else if (root.val < q.val && root.val < p.val){
            return lowestCommonAncestor(root.right, p, q);
        }
        else {
            return root;
        }
    }
}
/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */
迭代
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode cur = root;
        while (true){
            if (cur.val > p.val && cur.val > q.val){
                cur = cur.left;
            }
            else if (cur.val < p.val && cur.val < q.val){
                cur = cur.right;
            }
            else {
                break;
            }
        }
        return cur;
    }
}
/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号