Solution By Dare2Solve | Detailed Explanation | Clean Code
Explanation []\nauthorslog.com/blog/trMIXUEuGr\n\n# Code\n\ncpp []\nclass Solution {\npublic:\n    int kthSmallest(TreeNode* root, int k) {\n        int n = 0;\
```Explanation []\nauthorslog.com/blog/trMIXUEuGr\n```\n# Code\n\n```cpp []\nclass Solution {\npublic:\n    int kthSmallest(TreeNode* root, int k) {\n        int n = 0;\n        stack<TreeNode*> stk;\n        TreeNode* current = root;\n        \n        while (current || !stk.empty()) {\n            while (current) {\n                stk.push(current);\n                current = current->left;\n            }\n            current = stk.top();\n            stk.pop();\n            n += 1;\n            if (n == k) return current->val;\n            current = current->right;\n        }\n        return -1;\n    }\n};\n```\n\n```python []\nclass Solution:\n    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:\n        stack = []\n        current = root\n        n = 0\n\n        while current or stack:\n            while current:\n                stack.append(current)\n                current = current.left\n            current = stack.pop()\n            n += 1\n            if n == k:\n                return current.val\n            current = current.right\n        \n        return -1  # This return is just to satisfy the function signature, the function should always return within the loop if k is valid.\n```\n\n```java []\nclass Solution {\n    public int kthSmallest(TreeNode root, int k) {\n        Stack<TreeNode> stack = new Stack<>();\n        TreeNode current = root;\n        int n = 0;\n\n        while (current != null || !stack.isEmpty()) {\n            while (current != null) {\n                stack.push(current);\n                current = current.left;\n            }\n            current = stack.pop();\n            n++;\n            if (n == k) return current.val;\n            current = current.right;\n        }\n\n        return -1;\n    }\n}\n```\n\n```javascript []\nvar kthSmallest = function(root, k) \n{\n    let n = 0\n    let stack = []\n    let current = root\n    while (current || stack.length > 0) \n    {\n        while (current) {\n            stack.push(current)\n            current = current.left\n        }\n        current = stack.pop()\n        n += 1\n        if (n === k) return current.val\n        current = current.right\n    }\n};\n```
['Tree', 'Binary Search Tree', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']