题目
思路
- 由于是求第K小,直接按照左 中 右的顺序遍历。
代码
class Solution {
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
int count = 0;
while (!stack.isEmpty() || node != null) {
if (node != null) {
stack.push(node);
node = node.left;
} else {
TreeNode father = stack.pop();
count++;
if (count == k) {
return father.val;
}
node = father.right;
}
}
return 0;
}
}