题目描述
题目链接:173. Binary Search Tree Iterator
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()
andhasNext()
should run in average O(1) time and uses O(h) memory, where h is the height of the tree.- You may assume that
next()
call will always be valid, that is, there will be at least a next smallest number in the BST whennext()
is called.
解题思路
这道题比较简单的做法是在构造函数通过前序遍历将二叉树遍历一遍并将结果放入一个队列中,这样查询和返回下一元素都只需要常数时间,代码如下:
1 | /** |
- 时间复杂度: O(n) for constructor, O(1) for the other twos operations
- 空间复杂度: O(n) for constructor, O(1) for the other twos operations
GitHub 代码同步地址: 173.BinarySearchTreeIterator.cpp
其他题目:
GitHub: Leetcode-C++-Solution
博客: Leetcode-Solutions