-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path173.二叉搜索树迭代器.java
63 lines (53 loc) · 1.19 KB
/
173.二叉搜索树迭代器.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
* @lc app=leetcode.cn id=173 lang=java
*
* [173] 二叉搜索树迭代器
*/
// @lc code=start
/**
* 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 {
TreeNode cur;
Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
this.cur=root;
this.stack=new Stack<>();
}
public int next() {
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
cur=stack.pop();
int val=cur.val;
cur=cur.right;
return val;
}
public boolean hasNext() {
if(!stack.isEmpty()||cur!=null){
return true;
}else{
return false;
}
}
}
/**
* 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();
*/
// @lc code=end