首页 > 其他 > 详细

LeetCode OJ:Binary Search Tree Iterator(二叉搜索树迭代器)

时间:2015-10-24 00:09:23      阅读:297      评论:0      收藏:0      [点我收藏+]

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.

相当于遍历二叉搜索树,借助栈即可实现:

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 
11 class BSTIterator {
12 private:
13     stack<TreeNode *> stk;
14     TreeNode * node;
15 public:
16     BSTIterator(TreeNode *root) {
17         node = root;
18     }
19 
20     /** @return whether we have a next smallest number */
21     bool hasNext() {
22         return (node || !stk.empty());
23     }
24 
25     /** @return the next smallest number */
26     int next() {
27         TreeNode * res = NULL;
28         if(node == NULL){
29             res = stk.top();
30             stk.pop();
31             node = res->right;
32         }else{
33             while(node->left != NULL){
34                 stk.push(node);
35                 node = node->left;
36             }
37             res = node;
38             node = node->right;
39         }
40         return res->val;
41     }
42 };
43 
44 /**
45  * Your BSTIterator will be called like this:
46  * BSTIterator i = BSTIterator(root);
47  * while (i.hasNext()) cout << i.next();
48  */

 

LeetCode OJ:Binary Search Tree Iterator(二叉搜索树迭代器)

原文:http://www.cnblogs.com/-wang-cheng/p/4905881.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!