LeetCode(173) Binary Search Tree Iterator

来源:互联网 发布:java future get 阻塞 编辑:程序博客网 时间:2024/06/10 14:34

题目

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.

分析

实现二叉查找树的迭代器;

如题目描述,迭代器包括hasNext()和next()两个函数,其中hasNext()函数判断是否还有下一节点,next()函数返回节点元素值;且遍历顺序按照元素递增方式;

我们知道,对于二叉查找树的中序遍历结果为递增有序;所以此题的简单解法即是得到该二叉查找树的中序遍历序列并用queue保存;然后对queue进行处理;

AC代码

/** * 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) {           //中序遍历该二叉查找树,得到有序序列        inOrder(root, inOrderNodes);    }    /** @return whether we have a next smallest number */    bool hasNext() {        if (!inOrderNodes.empty())            return true;        return false;    }    /** @return the next smallest number */    int next() {        TreeNode *node = inOrderNodes.front();        inOrderNodes.pop();        return node->val;    }private:    queue<TreeNode *> inOrderNodes;    void inOrder(TreeNode *root, queue<TreeNode *> &inOrderNodes)    {        if (!root)            return;        if (root->left)            inOrder(root->left, inOrderNodes);        inOrderNodes.push(root);        if (root->right)            inOrder(root->right, inOrderNodes);    }};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
0 0
原创粉丝点击