Leetcode 235 "Lowest Common Ancestor of a Binary Search Tree"

January 1, 2022

Title

235. Lowest Common Ancestor of a Binary Search Tree

Result

Runtime: 20 ms, faster than 22.41% of Java online submissions for Lowest Common Ancestor of a Binary Search Tree. Memory Usage: 50.1 MB, less than 25.70% of Java online submissions for Lowest Common Ancestor of a Binary Search Tree.

/**
 * 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) {
        TreeNode head = root;
        while(true) {
            if(head == null)
                break;
            
            if(head.val <= q.val && head.val >= p.val
                || head.val >= q.val && head.val <= p.val) {
                return head;
            }
            if(p.val >= head.val) {
                head = head.right;
                continue;
            }
            if(q.val < head.val) {
                head = head.left;
                continue;
            }
        }
        return null;
    }
}