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.

 

 

复制代码
class BSTIterator {
public:
    stack<TreeNode*> stk;
    TreeNode* cur;
    BSTIterator(TreeNode* root) {
        cur = root;
    }
    
    int next() {
        int ret;
        while(cur != nullptr) {
            stk.push(cur);
            cur = cur->left;
        }
        cur = stk.top();
        stk.pop();
        ret = cur->val;
        cur = cur->right;
        return ret;
    }
    
    bool hasNext() {
        return (cur != nullptr || !stk.empty());
    }
};
复制代码

 

 

 

 

 

复制代码
 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 
11 public class BSTIterator {
12     private Stack<TreeNode> stack = new Stack<TreeNode>();
13     public BSTIterator(TreeNode root) {
14         pushAll(root);
15     }
16 
17     /** @return whether we have a next smallest number */
18     public boolean hasNext() {
19         return !stack.isEmpty();
20     }
21 
22     /** @return the next smallest number */
23     public int next() {
24         TreeNode node = stack.pop();
25         pushAll(node.right);
26         return node.val;
27         
28     }
29     private void pushAll(TreeNode node){
30         while(node != null){
31             stack.push(node);
32             node = node.left;
33         }
34             
35     }
36 }
37 
38 /**
39  * Your BSTIterator will be called like this:
40  * BSTIterator i = new BSTIterator(root);
41  * while (i.hasNext()) v[f()] = i.next();
42  */
复制代码

 

 

posted @   乐乐章  阅读(137)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core GC计划阶段(plan_phase)底层原理浅谈
· .NET开发智能桌面机器人:用.NET IoT库编写驱动控制两个屏幕
· 用纯.NET开发并制作一个智能桌面机器人:从.NET IoT入门开始
· 一个超经典 WinForm,WPF 卡死问题的终极反思
· ASP.NET Core - 日志记录系统(二)
阅读排行:
· 支付宝事故这事儿,凭什么又是程序员背锅?有没有可能是这样的...
· https证书一键自动续期,帮你解放90天限制
· 在线客服系统 QPS 突破 240/秒,连接数突破 4000,日请求数接近1000万次,.NET 多
· 推荐几个不错的 Linux 服务器管理工具
· C# 开发工具Visual Studio 介绍
点击右上角即可分享
微信分享提示