Search code examples
javaalgorithmbinary-search-tree

BST, is it possible to find next lowest in O(lg N)?


The TreeNode class is defined with only left and right child.

public class TreeNode {

    public int val;
    public TreeNode left, right;

    public TreeNode(int val) {
        this.val = val;
    }
}

My code finds the next lowest node in O(n). I was wondering if it's possible to find it in lg(N) given that the node doesn't have a pointer to its parent node.

// run time O(n)
    public static Integer findNextLowest(TreeNode root, int target) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || stack.size() > 0) {

            while (cur != null) {
                stack.push(cur);
                cur = cur.right;
            }
            TreeNode node = stack.pop();
            if (node.val < target) return node.val; // found the next lowest
            cur = node.left;
        }
        return null;
    }

Solution

  • private static TreeNode findNextLowest(TreeNode root, int target){
        TreeNode node = root;
        TreeNode res = null;
        while(node != null){
            while(node != null && node.val >= target){
                node = node.left;
            }
            while(node != null && node.val < target){
                res = node;
                node = node.right;
            }
        }
        return res;
    }