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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值