1. Inorder Traversal Array Scan
Intuition
Since in-order traversal yields elements in ascending order, the first element with value >= X is the ceil.
Algorithm
- Collect all tree values into a list using in-order traversal.
- Iterate through sorted values: if val >= X, return val.
- If no such value is found, return -1.
Inorder Array Scan for X = 5
2 of 2 questions left todayInorder traversal produces sorted list: [2, 4, 6, 8, 12]
Inorder traversal produces sorted list: [2, 4, 6, 8, 12].
#include <iostream>#include <vector> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}}; class Solution { void inorder(TreeNode* root, std::vector<int>& arr) { if (!root) return; inorder(root->left, arr); arr.push_back(root->val); inorder(root->right, arr); }public: int findCeil(TreeNode* root, int X) { std::vector<int> arr; inorder(root, arr); for (int v : arr) { if (v >= X) return v; } return -1; }}; int main() { TreeNode* root = new TreeNode(8); root->left = new TreeNode(4); root->right = new TreeNode(12); root->left->left = new TreeNode(2); root->left->right = new TreeNode(6); Solution sol; std::cout << "Ceil of 5: " << sol.findCeil(root, 5) << " (Expected: 6)\n"; std::cout << "Ceil of 13: " << sol.findCeil(root, 13) << " (Expected: -1)\n"; return 0;}Time & Space Complexity
- Time complexity:
O(N) - Space complexity:
O(N)