博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器
阅读量:7112 次
发布时间:2019-06-28

本文共 1356 字,大约阅读时间需要 4 分钟。

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.

Credits:

Special thanks to  for adding this problem and creating all test cases.

 

这道题主要就是考二叉树的中序遍历的非递归形式,需要额外定义一个栈来辅助,二叉搜索树的建树规则就是左<根<右,用中序遍历即可从小到大取出所有节点。代码如下:

 

/** * 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) {        while (root) {            s.push(root);            root = root->left;        }    }    /** @return whether we have a next smallest number */    bool hasNext() {        return !s.empty();    }    /** @return the next smallest number */    int next() {        TreeNode *n = s.top();        s.pop();        int res = n->val;        if (n->right) {            n = n->right;            while (n) {                s.push(n);                n = n->left;            }        }        return res;    }private:    stack
s;};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */

 

转载地址:http://ncghl.baihongyu.com/

你可能感兴趣的文章
NIO 理解
查看>>
第十三章:通过UDP广播事件
查看>>
Ubuntu 实用包安装指令
查看>>
tomcat启动慢
查看>>
XML之JDOM解析
查看>>
YXcms第一届模板大赛开始咯
查看>>
maven 命令手动添加本地jar包
查看>>
ECSHOP商品页加入购物车弹出层仿淘宝效果
查看>>
数据库的基本操作—查看数据库、选择表
查看>>
Java public ,protect,friendly,private的方法权限
查看>>
1.概述
查看>>
3.IP:网际协议
查看>>
qtp找不到对象
查看>>
jquery的常用技巧(二)
查看>>
Cocos2dx学习笔记11:cocos2dx调度器(scheduler)
查看>>
Java异常处理总结
查看>>
Oracle数据库SQL优化的最佳思路
查看>>
SCWS入门使用指南
查看>>
简单的进度条,圆形进度条(一)
查看>>
全表扫描、索引扫描与物理读
查看>>