Striver's Easy And Detailed Explanation
Approach\nStep 1: Perform inorder traversal from the root node. At every visited node, increment a counter variable to keep track of visited nodes. Inorder Trav
# Approach\n**Step 1:** Perform inorder traversal from the root node. At every visited node, increment a counter variable to keep track of visited nodes. Inorder Traversal: Traverse the left subtree, then current node then right subtree.\n\n**Step 2:** When the counter reaches K, store the value of the current node as the Kth smallest.\n\n**Step 3:** Return this value as the Kth smallest.\n\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    public int kthSmallest(TreeNode root, int k) {\n        int[] count = new int[]{0};\n        int[] kthSmallest = new int[]{Integer.MIN_VALUE};\n        inorderHelper(root, count, k, kthSmallest);\n        return kthSmallest[0];\n    }\n\n    public void inorderHelper(TreeNode root, int[] count, int k, int[] kthSmallest){\n        if (root == null || count[0] >= k) return;\n        // Traverse left subtree\n        inorderHelper(root.left, count, k, kthSmallest);\n\n        // Increment counter after visiting left subtree\n        count[0]++;\n\n        // Check if current node is the Kth smallest\n        if (count[0] == k) {\n            kthSmallest[0] = root.val;\n            return;\n        }\n\n        // Traverse right subtree if Kth smallest is not found yet\n        inorderHelper(root.right, count, k, kthSmallest);   \n    }\n}\n```\n# Upvote: \n![billa.gif](https://assets.leetcode.com/users/images/8e98a30a-f394-4b97-9710-d5829cef2896_1720072520.8153322.gif)\nThis is a tree series solution, please upvote if you find this helpful.\n
['Depth-First Search', 'Binary Search Tree', 'Java']