• 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.

    解题思路:

    实现一个基于二叉搜索树的类iterator。初始化iterator为这棵树的根节点root.。

    调用next()函数返回这棵树的下一个最小的值。

    方法:

    二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树。或者是具有下列性质的二叉树: 若它的左子树不空。则左子树上全部结点的值均小于它的根结点的值。 若它的右子树不空,则右子树上全部结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。比方:

    由此我们能够知道,对二叉搜索树进行中序遍历,便可得到升序的序列。

    所以在此题中我们利用迭代的方法实现二叉搜索树的中序遍历,參考我的博客http://blog.csdn.net/sinat_24520925/article/details/45621865可知,我们用栈来存储每次读取的节点,每次出栈的元素也就是我们读取的元素。

    所以我们仅仅要读取每次出栈的栈顶元素也就知道了这个时候二叉搜索树的next()节点了。

    代码例如以下:
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class BSTIterator {
        stack<TreeNode*> qu;
    public:
        BSTIterator(TreeNode *root) {
            push_in_stack(root);
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return !qu.empty();
            
        }
    
        /** @return the next smallest number */
        int next() {
            TreeNode *tmpNode = qu.top();
            qu.pop();
            push_in_stack(tmpNode->right);
            return tmpNode->val;
        }
    private:
    void push_in_stack(TreeNode* node)
    {
        while(node)
        {
            qu.push(node);
            node=node->left; 
        }
    }
    };
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */

    值得注意的是,本题要求不是输出root为根节点的树的最小值。而是要不断输出下一个最小值。

    所以在int next()函数中,我们不能输出栈顶元素就直接退出,完毕工作。而是要将输出元素的右子树插入栈中,继续读取以此栈顶元素为根节点的子树的最小值,也就是大树的下一个最小值。这样便实现了这种要求(源源不断的输出下一个最小值):

    while (i.hasNext()) cout << i.next();


  • 相关阅读:
    代码优化
    使用python的Flask实现一个RESTful API服务器端
    数据结构与算法之排序
    Ubuntu 13.04/12.10安装Oracle 11gR2图文教程(转)
    Linux 下开启ssh服务(转)
    PLSQL Developer 9.如何设置查询返回所有纪录(转)
    linux下安装oracle11g 64位最简客户端(转)
    Linux下关于解决JavaSwing中文乱码的情况(转)
    servlet(jsp)中的重定向和转发
    在用TabbarController中出现navigationController 嵌套报错
  • 原文地址:https://www.cnblogs.com/blfshiye/p/5257835.html
Copyright © 2020-2023  润新知