工作时做一道题好难。。。
最基本的中序遍历!
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int kthSmallest(TreeNode root, int k) {
if (root == null) {
return 0;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
int count = 1;
while (!stack.isEmpty()) {
TreeNode node = stack.peek();
if (node.left != null) {
stack.push(node.left);
node.left = null;
} else {
if (count == k) {
return node.val;
}
count++;
stack.pop();
if (node.right != null) {
stack.push(node.right);
}
}
}
return 0;
}
}