Leetcode 173.二叉搜索树迭代器

173. 二叉搜索树迭代器

题目

实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。

调用 next() 将返回二叉搜索树中的下一个最小的数。

1
2
3
4
5
6
7
8
9
10
11
示例:
BSTIterator iterator = new BSTIterator(root);
iterator.next(); // 返回 3
iterator.next(); // 返回 7
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 9
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 15
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 20
iterator.hasNext(); // 返回 false

方法

方法1:非递归中序遍历

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
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class BSTIterator(object):

def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack=[]
while root:
self.stack.append(root)
root=root.left


def next(self):
"""
@return the next smallest number
:rtype: int
"""
t=self.stack.pop()
x=t.right
while x:
self.stack.append(x)
x=x.left
return t.val


def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
return len(self.stack)>0


# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
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
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class BSTIterator(object):

def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack=[]
self.LeftToStack(root)

def next(self):
"""
@return the next smallest number
:rtype: int
"""
node=self.stack.pop()
self.LeftToStack(node.right)
return node.val

def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
return bool(self.stack)

def LeftToStack(self,root):
while root:
self.stack.append(root)
root=root.left

# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
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
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class BSTIterator(object):

def __init__(self, root):
"""
:type root: TreeNode
"""
self.root=root
self.stack=[]


def next(self):
"""
@return the next smallest number
:rtype: int
"""
while self.root:
self.stack.append(self.root)
self.root=self.root.left
node=self.stack.pop()
self.root=node.right
return node.val


def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
return bool(self.stack) or bool(self.root)



# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()