-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path173.binary-search-tree-iterator.java
More file actions
101 lines (91 loc) · 2.67 KB
/
Copy path173.binary-search-tree-iterator.java
File metadata and controls
101 lines (91 loc) · 2.67 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.util.ArrayList;
import java.util.Stack;
import javax.swing.tree.TreeNode;
/*
* @lc app=leetcode id=173 lang=java
*
* [173] Binary Search Tree Iterator
*/
// @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 {
Stack<TreeNode> mNodeStack;
public BSTIterator(TreeNode root) {
mNodeStack = new Stack<>();
while (root != null) {
mNodeStack.add(root);
root = root.left;
}
}
/** @return the next smallest number */
public int next() {
TreeNode currNode = mNodeStack.pop();
if (currNode.right != null) {
TreeNode currNodeNext = currNode.right;
while (currNodeNext != null) {
mNodeStack.add(currNodeNext);
currNodeNext = currNodeNext.left;
}
}
return currNode.val;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !mNodeStack.isEmpty();
}
// // 先inorder把整个bst转变成一个arraylist
// List<Integer> mBSTArray;
// int currIdx;
// public BSTIterator(TreeNode root) {
// mBSTArray = new ArrayList<>();
// Stack<TreeNode> nodeSt = new Stack<>();
// while (root != null) {
// nodeSt.add(root);
// root = root.left;
// }
// while (!nodeSt.isEmpty()) {
// TreeNode currNode = nodeSt.pop();
// mBSTArray.add(currNode.val);
// if (currNode.right != null) {
// TreeNode rightLeftNode = currNode.right;
// while (rightLeftNode != null) {
// nodeSt.add(rightLeftNode);
// rightLeftNode = rightLeftNode.left;
// }
// }
// }
// currIdx = -1;
// }
// /** @return the next smallest number */
// public int next() {
// if (!hasNext()) {
// return -1;
// }
// return mBSTArray.get(++currIdx);
// }
// /** @return whether we have a next smallest number */
// public boolean hasNext() {
// return currIdx + 1 < mBSTArray.size();
// }
}
/**
* 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