Binary Search Tree Iterator 173
题目描述:
对于一个二叉查找树,设计一个迭代器,每次调用会返回下一个最小值
题目分析:
没什么好说的二叉树的先序遍历
代码:
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 TreeNode *p=NULL; 12 stack<TreeNode *> stk; 13 void toLeft(TreeNode *root){ 14 p=root; 15 16 while(p && p->left){ 17 stk.push(p); 18 p=p->left; 19 } 20 } 21 public: 22 BSTIterator(TreeNode *root) { 23 if(root==NULL)p=NULL; 24 else { 25 toLeft(root); 26 } 27 } 28 29 /** @return whether we have a next smallest number */ 30 bool hasNext() { 31 return p; 32 } 33 34 /** @return the next smallest number */ 35 int next() { 36 int ret=p->val; 37 if(p->right){ 38 toLeft(p->right); 39 }else { 40 if(stk.empty())p=NULL; 41 else { 42 p=stk.top(); 43 stk.pop(); 44 //toLeft(p->right); 45 } 46 } 47 return ret; 48 } 49 }; 50 51 /** 52 * Your BSTIterator will be called like this: 53 * BSTIterator i = BSTIterator(root); 54 * while (i.hasNext()) cout << i.next(); 55 */