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();


原文地址:https://www.cnblogs.com/blfshiye/p/5257835.html