leetcode 230.二叉搜索树中第k小的元素
思路:中序遍历即可
只不过我们在中序遍历的时候需要一边遍历一边判断。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int kthSmallest(TreeNode root, int k) {
List<Integer>list=new ArrayList<>();
Deque<TreeNode>stk=new LinkedList<>();
while(root!=null||!stk.isEmpty()){
while(root!=null){
stk.push(root);
root=root.left;
}
TreeNode tmp=stk.pop();
k--;
if(k==0){
return tmp.val;
}
root=tmp.right;
}
return -1;
}
}