https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/
给出一个二叉搜索树,写出一个方法,求出树中的第k小的数
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
class Solution {
//中序遍历-栈
public int kthSmallest(TreeNode root, int k){
if(root==null || k==0) return -1;
Stack<TreeNode> s = new Stack<TreeNode>();
TreeNode node = root;
int knum=0;
s.add(node);
while(node!=null || !s.isEmpty()){
//左边入栈
while(node!=null){
s.add(node);
node=node.left;
}
//相当于访问极小点
node = s.pop();
knum++;
if(knum==k){
return node.val;
}
node = node.right;
}
return -1;
}
}