forked from leetcoders/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearchTreeIterator.java
100 lines (87 loc) · 2.52 KB
/
BinarySearchTreeIterator.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
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
/*
Author: king, [email protected]
Date: Dec 31, 2014
Problem: Binary Search Tree Iterator
Difficulty: Easy
Source: https://oj.leetcode.com/problems/binary-search-tree-iterator/
Notes:
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
Solution: Inorder traversal.
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator_1 {
public BSTIterator(TreeNode root) {
stk = new Stack<TreeNode>();
node = root;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if (stk.isEmpty() == true && node == null) return false;
return true;
}
/** @return the next smallest number */
public int next() {
if (stk.isEmpty() == true && node == null) return 0;
while (node != null) {
stk.push(node);
node = node.left;
}
int res = 0;
node = stk.pop();
res = node.val;
node = node.right;
return res;
}
private Stack<TreeNode> stk;
private TreeNode node;
}
public class BSTIterator_2 {
public BSTIterator(TreeNode root) {
node = root;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return node != null;
}
/** @return the next smallest number */
public int next() {
if (node == null) return 0;
int res = 0;
while (node != null) {
if (node.left == null) {
res = node.val;
node = node.right;
return res;
}
TreeNode pre = node.left;
while (pre.right != null && pre.right != node)
pre = pre.right;
if (pre.right == null) {
pre.right = node;
node = node.left;
} else {
res = node.val;
node = node.right;
pre.right = null;
return res;
}
}
return res;
}
private TreeNode node;
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/