Best O(N) Solution
Approach 1\nPreorder Traversal\n\n# Complexity\n- Time complexity:\nO(nlogn) \n\n- Space complexity:\nO(n) \n\n# Code\n\n/**\n * Definition for a binary tree no
# Approach 1\nPreorder Traversal\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$$ \n\n- Space complexity:\n$$O(n)$$ \n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    int kthSmallest(TreeNode* root, int k) {\n        vector <int> nodes;\n        traversal(root, nodes);\n        sort(nodes.begin(), nodes.end());\n        return nodes[k-1];\n    }\n\n    void traversal(TreeNode* root, vector <int>& nodes) {\n        if (root == NULL)\n            return;\n        nodes.push_back(root->val);\n        traversal(root->left, nodes);\n        traversal(root->right, nodes);    \n    }\n};\n```\n\n# Approach 2\nInorder Traversal\n\n# Complexity\n- Time complexity:\n$$O(h)$$ --> h is height of the BST \n\n- Space complexity:\n$$O(h)$$ --> h is height of the BST \n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    int kthSmallest(TreeNode* root, int k) {\n        TreeNode* kthSmallest = traversal(root, k);\n        return kthSmallest->val;\n    }\n\n    TreeNode* traversal(TreeNode* root, int& k) {\n        if (root == NULL)\n            return NULL;\n        TreeNode* left = traversal(root->left, k);\n        if (left != NULL)\n            return left;\n        k--;    \n        if (k == 0)\n            return root;\n        return traversal(root->right, k);    \n    }\n};\n```
['C++']