Untitled
public int kthSmallest(TreeNode root, int k) { Stack<TreeNode> stack = new Stack<>(); TreeNode current = root; while (!stack.isEmpty() || current != null) { // Traverse the left subtree while (current != null) { stack.push(current); current = current.left; } // Process the current node current = stack.pop(); k--; if (k == 0) { return current.val; } // Traverse the right subtree current = current.right; } return -1; // If k is invalid }
Leave a Comment