173.leetcode Binary Search Tree Iterator(medium)[二叉搜索树 栈 中序遍历]

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.

传统的中序遍历采用递归的方式就可以顺序读取二叉搜索树中的内容,但是由于程序栈很很深具有较大的开销,因此采用一个栈来记录之前的路径,采用迭代的方式完成遍历更加高效。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
public:
    //采用中序遍历可以按照从小到大遍历BST,这里是实现中序遍历器的含义,定义一个stack记录之前的位置
    stack<TreeNode*> s;
    TreeNode* current = NULL;//记录当前节点左子树的指针,对于当前节点的下一个最小节点可能是current的最左子树,如果current为空表示
//上一次遍历的节点没有右子树,就从栈中取
    BSTIterator(TreeNode *root) {
        current = root;
        /*while(node->left != NULL)
        {    
            s.push(node);
            node = node->left;
        }
        current = node;*/
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
         return !(current==NULL && s.empty());
    }

    /** @return the next smallest number */
    int next() {
        TreeNode *temp = NULL;
        if(current == NULL)
        {
            if(!s.empty())
            {
                temp = s.top();
                s.pop();
                current = temp->right;
            }
        }else 
        {   
                while(current->left != NULL)
                {
                    s.push(current);
                    current = current->left;
                }
                temp = current;
                current = current->right;
        }
        return temp->val;   
    }
};

/**
 * 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、付费专栏及课程。

余额充值