思路:栈。
- 题目要求从小到大返回节点的值,那就是中序遍历,我们可以用一个数组,存储中序遍历的结果,这样可以满足需求,空间复杂度是O(n),n是节点数。
- 可以借助栈实现树的中序遍历。按照这个思路,栈顶元素总是当前的最小值,每弹出一个元素,若不是叶节点,就要再次进行压栈。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class BSTIterator {
private Stack<TreeNode> s;
public BSTIterator(TreeNode root) {
s = new Stack<TreeNode>();
push(root);
}
public void push(TreeNode root) {
while (root != null) {
s.push(root);
root = root.left;
}
}
public int next() {
TreeNode temp = s.pop();
push(temp.right);
return temp.val;
}
public boolean hasNext() {
if (s.isEmpty()) {
return false;
}
return true;
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/