1. Inorder Traversal Array Scan
Intuition
Traverse the entire BST using inorder DFS, appending node references into an array. Find index i where arr[i] == x. If i + 1 < arr.length, return arr[i + 1]. Otherwise return null. This takes O(N) time and O(N) space.
When to apply: Baseline brute force when memory and time are unrestricted.
Algorithm
- Collect all nodes in an array via full inorder traversal, find node x, and return the next node in the array.
#include <iostream>#include <vector> struct Node { int data; Node* left; Node* right; Node(int val) : data(val), left(nullptr), right(nullptr) {}}; class Solution { void inorder(Node* root, std::vector<Node*>& nodes) { if (!root) return; inorder(root->left, nodes); nodes.push_back(root); inorder(root->right, nodes); }public: Node* inOrderSuccessor(Node* root, Node* x) { std::vector<Node*> nodes; inorder(root, nodes); for (int i = 0; i < (int)nodes.size(); i++) { if (nodes[i] == x) { if (i + 1 < (int)nodes.size()) return nodes[i + 1]; return nullptr; } } return nullptr; }}; int main() { Node* root = new Node(20); root->left = new Node(8); root->right = new Node(22); root->left->left = new Node(4); root->left->right = new Node(12); root->left->right->left = new Node(10); root->left->right->right = new Node(14); Solution sol; Node* succ = sol.inOrderSuccessor(root, root->left); // Successor of 8 std::cout << "Successor of 8: " << (succ ? succ->data : -1) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) - Space complexity:
O(N)