码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Binary Tree Iterator

时间:2015-03-18 07:50:34      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

It is similar to use stack for BST inorder traversal.

So do the same thing : 

1. Get stack to store right branchs (include current node).

2. When you pop the top node, remember to push all the right sub branches again. Otherwise, it will cause right‘s left branches missed from result

 

 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 class BSTIterator {
11 private:
12     stack<TreeNode *> s;
13 public:
14     void initialNodes(TreeNode *root) {
15         while (root) {
16             s.push(root);
17             root = root->left;
18         }
19     }
20     BSTIterator(TreeNode *root) {
21         initialNodes(root);
22     }
23 
24     /** @return whether we have a next smallest number */
25     bool hasNext() {
26         return !s.empty();
27     }
28 
29     /** @return the next smallest number */
30     int next() {
31         TreeNode *tmp = s.top();
32         s.pop();
33         if (tmp->right) {
34             initialNodes(tmp->right);
35         }
36         return tmp->val;
37     }
38 };
39 
40 /**
41  * Your BSTIterator will be called like this:
42  * BSTIterator i = BSTIterator(root);
43  * while (i.hasNext()) cout << i.next();
44  */

 

LeetCode – Refresh – Binary Tree Iterator

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4346167.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!