中序遍历,寻找第k小
class Solution {
List<Integer> list = new ArrayList<>();
public int kthSmallest(TreeNode root, int k) {
dfs(root);
int count = 0;
for (Integer param : list) {
if (++count == k)
return param;
}
return -1;
}
public void dfs(TreeNode root) {
if (root == null)
return;
dfs(root.left);
list.add(root.val);
dfs(root.right);
}
}