题目来源:
https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/
题目描述:
代码如下:
/**
* 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) {
int count = 0;
Stack<TreeNode> stack = new Stack<>();
while(root!=null||!stack.empty()) {
while(root!=null) {
stack.push(root);
root=root.left;
}
root=stack.pop();
count++;
if(count==k) {
return root.val;
}
root=root.right;
}
return 0;
}
}