LeetCode 235 Lowest Common Ancestor of a Binary Search Tree

思路

由于是BST,思路相比与236题有所简化。
只需要判断2个目标是否都在同一分支即可。

递归实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    // recursively
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(p.val > root.val && q.val > root.val)
            return lowestCommonAncestor(root.right, p, q);
        if(p.val < root.val && q.val < root.val)
            return lowestCommonAncestor(root.left, p, q);
        
        return root;
    }
}

时间复杂度O(n)
空间复杂度O(n)

迭代实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    // iteratively
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        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 null;
    }
}

时间复杂度O(n)
空间复杂度O(1)

猜你喜欢

转载自blog.csdn.net/qq_36754149/article/details/88600100