Untitled
unknown
plain_text
10 months ago
679 B
3
Indexable
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
}Editor is loading...
Leave a Comment