【LeetCode 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()
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 ...
随机推荐
- Mybatis全部查询遇到的返回类型的小问题
在学习Mybatis3过程中遇到一个小问题,觉得需要注意就把它写下来了 在查询所有数据的时候方法是这样的 public List<User> findAll(){ ..... } 在它的u ...
- Unix编程之size_t、ssize_t
http://blog.csdn.net/lalor/article/details/7426184 首先,我非常肯定以 及确定的告诉你ssize_t是有符号整型,在32位机器上等同与int,在64位 ...
- NGUI中Button与原生2D精灵的混合使用
一些废话 每一篇的首段都是这个“一些废话”,原因是我太能逼逼了,不逼逼一些废话我就觉得难受.这是我第四篇关于Unity的博文,前两篇还是去年写的,“从一点儿不会开始”系列,类似教程和学习笔记的博文,这 ...
- Quartz的任务的临时启动和暂停和恢复
Quartz的任务的临时启动和暂停和恢复 在项目中需要手动启停某些服务,那么需要有一个控制这些任务的类.由于任务是有Quartz控制的,我们只需要通过Quartz的相关的API实现相关的功能即可. p ...
- 基于Struts2框架实现登录案例 之 程序国际化
国际化牵涉的知识非常多,这里只能简单的介绍,程序国际化的一般做法是:在jsp页面时, 不是直接输出信息,而是输出一个key值,该key值在不同语言环境下找到对应资源文件下的 对应信息,因此首先要创建满 ...
- C# 调用命令行,参数有空格
在程序中调用cmd命令打开一个文件,而文件路径带有空格,如果直接把路径传给cmd,那么cmd就会把路径空格前面的部分当做是一个参数,空格后当做另一个参数,命令行执行把后边截掉了,导致程序出错,会弹出了 ...
- Java API —— IO流( FileInputStream & FileOutputStream & BufferedInputStream & BufferedOutputStream )
1.IO流概述 · IO流用来处理设备之间的数据传输 · 上传文件和下载文件 · Java对数据的操作是通过流的方式 · Java用于操作流的对象都在IO包中 2.IO ...
- java教材
教材blog !!http://www.w3cschool.cc/java/java-tutorial.html ok http://www.douban.com/group/topic/ ...
- 怎么在eclipse里调试WebDriver的源代码
当你看完WebDriver的工作原理这篇博客以后,是不是也跃跃欲试想印证文章里的理论是不是正确,想自己也看下webdriver的源代码,并且调试下,通过代码来更深入的了解WebDriver的工作原理. ...
- tuxedo入门
为文件增加用户执行权限: 官网下载tuxedo111120_64_Linux_01_x86.bin su //进入root操作,防止权限不够 创建文件夹,用来做tuxedo文件的安装路径 cd /op ...