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. Perl 三种时间time,localtime,gmttime

    #!/usr/bin/perl use warnings; use diagnostics; use strict; use POSIX; print "time: ", time ...

  2. linux下用非root用户重启导致ssh无法连接的问题

    问题描述 安装好了centOS服务器,一直用Secure CRT工具通过ssh服务来远程连接linux,很方便的进行各种操作.今天偶然尝试了一下在非root的一般用户下执行重启服务器的命令,发现一般用 ...

  3. MIT算法导论——第四讲.Quicksort

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

  4. Hibernate逍遥游记-第13章 映射实体关联关系-001用外键映射一对一(<many-to-one unique="true">、<one-to-one>)

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  5. python 时间处理(time和datetime介绍)

    python的有关时间的有哪几种呢?今天我们介绍两个:time和datetime time模块提供各种操作时间的函数 datetime模块定义了下面这几个类: datetime.date:表示日期的类 ...

  6. 前端必杀技之Javascript 第1天

    学习了javascript基本语法和使用DOM进行简单操作   1.引用javascript方法: a.在<script></script>标签中加入js代码,如: <s ...

  7. 实用Photoshop快捷键

    面板快捷键:shift+对应的快捷键调用同类工具 Ctrl + 点击面板------获取选取 Shift + F6-----------羽化 Alt + Delete---------填充前景色 Ct ...

  8. [iOS]iPhone进行真机测试(基础版)

    买完688个人开发者账号之后,如何进行真机测试呢??看下面 1.打开https://developer.apple.com 然后,输入我们买过688点那个App ID帐号和密码哦!!一定是要支付过的! ...

  9. Android Andbase应用开发框架

    [运行说明]运行AndbaseDemo需要将文件中的Andbase库Add进demo中.1.andbase中包含了大量的开发常用手段.如网络下载,多线程与线程池的管理,数据库ORM,图片缓存管理,图片 ...

  10. WCF 简单示例

    WCF(Windows Communication Foundation,WCF)是基于Windows平台下开发和部署服务的软件开发包(Software Development Kit,SDK).WC ...