LeetCode---Binary Search Tree Iterator ---C++

来源:互联网 发布:网络教育怎么查学籍 编辑:程序博客网 时间:2024/05/17 04:41

问题描述:

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.

对BST,实现一个迭代器。

思路:对于BST,其中序遍历为排序的。中序遍历的非递归方法,就用到了一个栈。所以该题的思路就是用一个栈来实现。因此BST的迭代器类,有一个私有的stack,在构造函数中把BST中最左边的节点入栈。然后hasnext()函数返回true当栈中还有元素时。next,出栈,返回值为该节点的val,然后判断是否有右节点,若有,则把该节点及其所有左节点入栈。

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


0 0