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的更多相关文章

  1. 【leetcode】Binary Search Tree Iterator

    Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator wil ...

  2. 【leetcode】Binary Search Tree Iterator(middle)

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

  3. LeetCode(173) Binary Search Tree Iterator

    题目 Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ...

  4. LeetCode OJ:Binary Search Tree Iterator(二叉搜索树迭代器)

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

  5. 【LeetCode】173. Binary Search Tree Iterator (2 solutions)

    Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator wil ...

  6. 二叉树前序、中序、后序非递归遍历 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 前序的非递归遍历:用堆来实现 如果把这个代码改成先向堆存储左节点再存储右节点,就变成了每一行从右向左打印 如果用队列替代堆,并且 ...

  7. LeetCode: Binary Search Tree Iterator 解题报告

    Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator wil ...

  8. leetcode-173:Binary Search Tree Iterator(Java)

    Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator wil ...

  9. [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 ...

随机推荐

  1. Ubuntu环境下手动配置HBase0.94.25

    /×××××××××××××××××××××××××××××××××××××××××/ Author:xxx0624 HomePage:http://www.cnblogs.com/xxx0624/ ...

  2. linux 命令小例

    xargs示例: ls |xargs -i mv {}  /opt find示例: find -mtime +n -name “*.avi” -type f -exec rm {} \; find - ...

  3. JS事件(事件冒泡和事件捕获)

    事件流:描述的是在页面中接收事件的顺序 事件冒泡:由最具体的元素接收,然后逐级向上传播至最不具体的元素的节点(文档) 事件捕获:最不具体的节点先接收事件,而最具体的节点应该是最后接收事件 DOM中:用 ...

  4. lintcode:previous permutation上一个排列

    题目 上一个排列 给定一个整数数组来表示排列,找出其上一个排列. 样例 给出排列[1,3,2,3],其上一个排列是[1,2,3,3] 给出排列[1,2,3,4],其上一个排列是[4,3,2,1] 注意 ...

  5. MIT算法导论——第一讲.Analysis of algorithm

    本栏目(Algorithms)下MIT算法导论专题是个人对网易公开课MIT算法导论的学习心得与笔记.所有内容均来自MIT公开课Introduction to Algorithms中Charles E. ...

  6. Excel操作--使用NPOI导入导出Excel为DataTable

    1.ExcelHelper封装 namespace NPOI操作Excel { public class ExcelHelper { /// <summary> /// DataTable ...

  7. MyEclipse 2013 开发WebService

    1.在Package Explorer窗口右键File新建WebService Project项目,我的名称为:TestWebService 2.WebService Framework选择JAX-W ...

  8. mongodb group分组

    先插入测试数据: for(var i=1; i<20; i++){     var num=i%6;     db.test.insert({_id:i,name:"user_&quo ...

  9. 整理了一份招PHP高级工程师的面试题

    1. 基本知识点 HTTP协议中几个状态码的含义:1xx(临时响应) 表示临时响应并需要请求者继续执行操作的状态代码. 代码   说明 100   (继续) 请求者应当继续提出请求. 服务器返回此代码 ...

  10. AFNetworking使用

    1.访问网络获取Json //Get方法 NSString *str = @"http://api.xxx.cc/product/found.jhtml"; NSDictionar ...