zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    Credits:
    Special thanks to @ts for adding this problem and creating all test cases.

    Hide Tags
     Tree Stack
     

      题目的意思是给定一个bst,将全部数值 升序排列,next 从左到右输出一个值,havenext 输出时候还有未输出的值,需要做的是在class 内部维护这样的输出,同时满足一定的条件。
      方法是通过stack 来维护。
     
    #include <iostream>
    #include <stack>
    using namespace std;
    
    /**
     * Definition for binary tree
     */
    struct TreeNode {
        int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    };
    
    class BSTIterator {
    public:
        stack<TreeNode *> stk;
        BSTIterator(TreeNode *root) {
            TreeNode * node = root;
            while(node!=NULL){
                stk.push(node);
                node = node->left;
            }
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return stk.size()!=0;
        }
    
        /** @return the next smallest number */
        int next() {
            int retNum = (stk.top())->val;
            TreeNode* node = (stk.top())->right;
            stk.pop();
            while(node!=NULL){
                stk.push(node);
                node = node->left;
            }
            return retNum;
        }
    };
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */
    
     int main()
     {
         return 0;
     }
  • 相关阅读:
    使用密码记录工具keepass来保存密码
    ADO.NET Entity Framework CodeFirst 如何输出日志(EF 5.0)
    Mono 3.2 测试NPinyin 中文转换拼音代码
    Reactive Extensions(Rx) 学习
    Reactive Extensions介绍
    Mono 3.2 上跑NUnit测试
    RazorEngine 3.3 在Mono 3.2上正常运行
    标准数据源访问库
    .Net 跨平台可移植类库正在进行
    Windows安装和使用zookeeper
  • 原文地址:https://www.cnblogs.com/Azhu/p/4334800.html
Copyright © 2011-2022 走看看