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.
题意:
实现二分搜索树的hasNext() 以及next() 操作,要求 O(1) time and O(h) memory。
思路:
暴力的方法是遍历整个树然后将所有元素放入有序的队列中,依次取出,但空间复杂度为O(n)。O(h)的复杂度的解法可通过一个栈来实现:依次将最左边的元素压栈,每次弹出最左下的元素即为最小的元素,同时判断其是否有右子树,若有右子树则继续将其右结点的左边元素依次压栈,循环直到栈为空。
C++:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public: BSTIterator(TreeNode *root):_min() {
while(root != )
{
_stack.push(root);
root = root->left;
}
} /** @return whether we have a next smallest number */
bool hasNext() { if(_stack.empty())
return false;
else
{
TreeNode* curNode = _stack.top();
_min = curNode->val;
_stack.pop(); if(curNode->right != )
{
TreeNode* newNode = curNode->right;
while(newNode != )
{
_stack.push(newNode);
newNode = newNode->left;
}
}
return true;
}
} /** @return the next smallest number */
int next() {
return _min;
} private:
stack<TreeNode*> _stack;
int _min;
}; /**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
Python:
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class BSTIterator:
# @param root, a binary search tree's root node
def __init__(self, root):
self.minval = 0
self.L = []
while root is not None:
self.L.append(root)
root = root.left # @return a boolean, whether we have a next smallest number
def hasNext(self):
if len(self.L) == 0:
return False
else:
curNode = self.L.pop()
self.minval = curNode.val if curNode.right is not None:
newNode = curNode.right
while newNode is not None:
self.L.append(newNode)
newNode = newNode.left return True # @return an integer, the next smallest number
def next(self):
return self.minval # Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next())
【LeetCode 173】Binary Search Tree Iterator的更多相关文章
-
【leetcode】Binary Search Tree Iterator
Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator wil ...
-
【leetcode】Binary Search Tree Iterator(middle)
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
-
LeetCode(173) Binary Search Tree Iterator
题目 Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ...
-
LeetCode OJ:Binary Search Tree Iterator(二叉搜索树迭代器)
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
-
【LeetCode】173. Binary Search Tree Iterator (2 solutions)
Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator wil ...
-
二叉树前序、中序、后序非递归遍历 144. Binary Tree Preorder Traversal 、 94. Binary Tree Inorder Traversal 、145. Binary Tree Postorder Traversal 、173. Binary Search Tree Iterator
144. Binary Tree Preorder Traversal 前序的非递归遍历:用堆来实现 如果把这个代码改成先向堆存储左节点再存储右节点,就变成了每一行从右向左打印 如果用队列替代堆,并且 ...
-
LeetCode: Binary Search Tree Iterator 解题报告
Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator wil ...
-
leetcode-173:Binary Search Tree Iterator(Java)
Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator wil ...
-
[LeetCode] 272. Closest Binary Search Tree Value II 最近的二叉搜索树的值 II
Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...
随机推荐
-
Oracle数据库BLOB字段的存取
述] Oracle的Blob字段比较特殊,他比long字段的性能要好很多,可以用来保存例如图片之类的二进制数据. 写入Blob字段和写入其它类型字段的方式非常不同,因为Blob自身有一个cur ...
-
How to browse the entire documentation using XCode 5 Documentation and API Reference ?
file:///Users/yangiori/Library/Developer/Shared/Documentation/DocSets/com.apple.adc.documentation.Ap ...
-
android之location02
package com.example.mars_3300_location02; import java.net.ContentHandler; import java.util.List; imp ...
-
sql server 数据库 数据DateTime 转mysql
首先将sql server DateTime 转换为varchar(50) 然后更新转换过的 DateTime字段, UPDATE 表名 SET LastUpdateTime=CONVERT(VAR ...
-
Nohttp请求图片的两种简答的方式:普通请求以及缓存请求
开局声明:这是基于nohttp1.0.4-include-source.jar版本写的教程 由于nohttp功能强悍,因此需要多种权限,仅仅一个联网的权限是不够的,如果只给了Internet的权限,去 ...
-
js 技巧1
1. 使用===取代== ==和!=操作符会在需要的情况下自动转换数据类型.但===和!==不会,它们会同时比较值和数据类型,这也使得它们要比==和!=快. "){ //速度慢 } & ...
-
[LeetCode] Decode Ways II 解码方法之二
A message containing letters from A-Z is being encoded to numbers using the following mapping way: ' ...
-
Java将string内容写入到TXT文件
private static String filePath = "E:\\test.txt"; private static void saveAsFileWriter(Stri ...
-
The web application registered the JDBC driver * but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
最近使用了最新版的tomcat9,使用jdbc链接mysql数据库.关闭tomcat过程中出现警告 13-Sep-2017 22:22:54.369 WARNING [main] org.apache ...
-
springfox+swagger2生成API文档
1.建立一个spring mvc工程: 2.添加POM依赖: <properties> <springfoxversion>2.6.1</springfoxversion ...