题目
代码
码源
解法1:
class Solution {
public int kthSmallest(TreeNode root, int k) {
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
while (true) {
while (root != null) {
stack.add(root);
root = root.left;
}
root = stack.removeLast();
if (--k == 0) return root.val;
root = root.right;
}
}
}
解法2,中序遍历法:
class Solution {
public int kthSmallest(TreeNode root, int k) {
ArrayList<Integer> nums = infixOrder(root, new ArrayList<Integer>());
return nums.get(k - 1);
}
private ArrayList<Integer> infixOrder(TreeNode root, ArrayList<Integer> arr) {
if (root == null) return arr;
infixOrder(root.left, arr);
arr.add(root.val);
infixOrder(root.right, arr);
return arr;
}
}