[C++]LeetCode: 93 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.

思路:题目的意思是,我们有一个已知的查找二叉树,然后我们设计一个迭代器,每次将最小的结点送给迭代器函数(BSTIterator i = BSTIterator(root);),然后去求下一个最小的值(while (i.hasNext()) cout << i.next();)。根据查找二叉树的存储特点,我们用非递归的中序遍历来实现。需要维护一个内置的栈,一个辅助函数,栈最开始先存储从该结点到最左叶子节点的路径,栈最上面的节点保存当前最小的节点(随迭代器移动而移动),如果该结点存在右孩子,再将其右孩子到最左侧叶子节点的路径放入栈中,也就是我们始终要维护栈的最上面的节点是当前最小节点。

Attention:

1. 注意题中是如何维护一个中序遍历结果的。最左-->最左的父结点-->以最左的兄弟节点的右子树(右子树又继续最左这个过程)

用栈来保存从根到最左侧叶子节点的路径,栈最上面的结点是最小的结点,每次取next,都是取栈最上面的结点,然后把剩余结点到最左侧叶子节点的路径放入栈中。

AC Code:

/**
 * 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) {
        //将当前节点的中序遍历加入结果
        pushAll(root);
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        //如果stack为空,说明此树中没有比当前节点更小的值了
        return !mystack.empty();
    }

    /** @return the next smallest number */
    int next() {
        TreeNode* tmp = mystack.top();
        mystack.pop();
        //中序遍历左子树后,遍历右子树
        pushAll(tmp->right);
        return tmp->val;
    }
    
private:
    stack<TreeNode*> mystack;
    void pushAll(TreeNode* node)
    {
        for(; node != NULL; )
        {
            mystack.push(node);
            node = node->left;
        }
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值