思路:二叉搜索树的中序遍历就是有序数组,所以取有序序列的第K个(两种方式:1.完整遍历,输出数组k-1 2.遍历k次,然后直接返回
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthSmallest(TreeNode root, int k) {//中序遍历,再ArrayList里寻找第k个
List<Integer> a = new ArrayList<>();
Stack<TreeNode> b = new Stack<>();
if(root == null) return 0;
int m = 0;
while(root != null || !b.isEmpty())
{
while(root != null)
{
b.push(root);
root = root.left;
}
root = b.pop();
a.add(root.val);
m++;
if(m == k) return root.val;
root = root.right;
}
return a.get(k-1) ;
}
}
)