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