This website uses cookies to enhance the user experience

In-Order Successor in Binary Search Tree

Difficulty: 💪🏽 Medium

Problem Statement

Given the root of a binary search tree and a node p in it, write a function to find the in-order successor of that node in the BST. The in-order successor of a node p is the node with the smallest key greater than p.val.

Example
Input: root = [2,1,3], p = 1
Output: 2

Input: root = [5,3,6,2,4,null,null,1], p = 6
Output: None
Constraints
  • The number of nodes in the tree is in the range [1, 10^4].
  • -10^5 <= Node.val <= 10^5
  • All Node.val are unique.

Expected Challenge Output

When the function inOrderSuccessor is called with the given example input, the expected output is the value of the in-order successor of the given node p, or None if no successor exists.

const root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(6);
root.left.left = new TreeNode(2);
root.left.right = new TreeNode(4);
root.left.left.left = new TreeNode(1);
let p = root.left;  // Node with value 3
console.log(new Solution().inOrderSuccessor(root, p).val);  // Output: 4

p = root.right;  // Node with value 6
console.log(new Solution().inOrderSuccessor(root, p));  // Output: null
class TreeNode {
constructor(val=0, left=null, right=null) {
this.val = val;
this.left = left;
this.right = right;
}
}

class Solution {
inOrderSuccessor(root, p) {
// YOUR SOLUTION HERE
}
}

Memory: 0

CPU: 0