leetcode Binary Search Tree Iterator

来源:互联网 发布:ppt如何修改图表数据 编辑:程序博客网 时间:2024/06/15 02:05

题目

原题链接:https://leetcode.com/problems/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.

分析

题目不好理解,说白了就是使用非递归的形式中序遍历二叉树,这也是c++的STL中关联容器迭代器的实现原型。非递归中序遍历二叉树的话就是借助栈,让下次输出的目标节点始终存放在栈顶位置。每次输出一个节点,就将此节点的后续节点放入栈中(沿着右子树的左子树一直向左就是下一个要输出的节点)。

代码

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class BSTIterator {private:    stack<TreeNode* > help_stack;public:    BSTIterator(TreeNode *root) {        TreeNode* p = root;        while(p){            help_stack.push(p);            p = p->left;        }    }    /** @return whether we have a next smallest number */    bool hasNext() {        return !help_stack.empty();    }    /** @return the next smallest number */    int next() {        TreeNode *result = help_stack.top();        help_stack.pop();        TreeNode *p = result->right;        while(p){            help_stack.push(p);            p = p->left;        }        return result->val;    }};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
0 0
原创粉丝点击