1. Inorder Traversal Array Scan
Intuition
Since in-order traversal of a BST gives sorted order, we can collect all elements into an array and find the last element <= X.
Algorithm
- Collect all tree values into a list using in-order traversal.
- Initialize floor = -1.
- Iterate through sorted values: if val <= X, update floor = val. If val > X, break.
- Return floor.
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 floorInBST(TreeNode* root, int X) { std::vector<int> arr; inorder(root, arr); int floorVal = -1; for (int v : arr) { if (v <= X) floorVal = v; else break; } return floorVal; }}; 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 << "Floor of 5: " << sol.floorInBST(root, 5) << " (Expected: 4)\n"; std::cout << "Floor of 1: " << sol.floorInBST(root, 1) << " (Expected: -1)\n"; return 0;}Time & Space Complexity
- Time complexity:
O(N) - Space complexity:
O(N)