1. Full Inorder Array Scan
Intuition
Traverse the tree inorder and record values in an array. Iterate through the array to find the last value < key (predecessor) and the first value > key (successor). Takes O(N) time and O(N) space.
When to apply: Baseline comparison when space is unrestricted.
Algorithm
- Extract sorted array via inorder traversal, then find the largest element < key and smallest element > key.
#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: void findPreSuc(Node* root, Node*& pre, Node*& suc, int key) { pre = nullptr; suc = nullptr; std::vector<Node*> nodes; inorder(root, nodes); for (Node* node : nodes) { if (node->data < key) pre = node; if (node->data > key && !suc) suc = node; } }}; int main() { Node* root = new Node(50); root->left = new Node(30); root->right = new Node(70); root->left->left = new Node(20); root->left->right = new Node(40); root->right->left = new Node(60); root->right->right = new Node(80); Solution sol; Node *pre = nullptr, *suc = nullptr; sol.findPreSuc(root, pre, suc, 65); std::cout << "Pre: " << (pre ? pre->data : -1) << ", Suc: " << (suc ? suc->data : -1) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) - Space complexity:
O(N)