![](https://i-blog.csdnimg.cn/blog_migrate/23a1ae1856293ff4edd814c41429ca1c.png)
暴力解法:
class Solution {
public int kthSmallest(TreeNode root, int k) {
List<Integer> list = new ArrayList<>();
Deque<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()){
TreeNode temp = queue.poll();
list.add(temp.val);
if(temp.left != null){
queue.offer(temp.left);
}
if(temp.right != null){
queue.offer(temp.right);
}
}
Integer[] arr = list.toArray(new Integer[list.size()]);
Arrays.sort(arr);
return arr[k - 1];
}
}
利用二叉搜索树 + 中序遍历性质
class Solution {
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<>();
while (root != null || !stack.isEmpty()){
while (root !=null){
stack.push(root);
root = root.left;
}
root = stack.pop();
k--;
if(k == 0){
return root.val;
}
root = root.right;
}
return -1;
}
}