8ms Java solution, easy to understand


  • 0

    public class Solution {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || p == null || q == null) { return null; }
        if(p.val < root.val && q.val < root.val) {
            return lowestCommonAncestor(root.left, p, q);
        } else if (p.val > root.val && q.val > root.val) {
            return lowestCommonAncestor(root.right, p, q);
        } else {
            return root;
        }
    }
    

    }


  • 0
    D

    What would the Time and Space complexity of this be?
    I'm thinking O(LogN) Time and O(logN) Space as well?


  • 0

    @DanielMan97 it's traversing all the nodes only once , so time complexity is O(n), space complexity is O(1) since no extra space allocated.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.