递归:
class Solution
{
int count=0;
int res=0;
public int kthSmallest(TreeNode root, int k) {
if(root.left!=null)
kthSmallest(root.left,k);
count++;
if(count==k)
{
res=root.val;
}
if(root.right!=null)
kthSmallest(root.right,k);
return res;
}
}
非递归:
class solution{
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack=new Stack<>();
int flag=0;
TreeNode p=root;
int res=0;
int count=0
//stack.push(root);
while(p!=null||!stack.isEmpty())
{
while(p!=null)
{
stack.push(p);
p=p.left;
}
if(!stack.isEmpty())
{
TreeNode t=stack.pop();
int tem=t.val;
count++;
if(count==k)
{
res=tem;
flag=1;
break;
}
p=t.right;
}
}
return res;
}
}