标签:
Design an iterator over a binary search tree with the following rules:
next()
and hasNext()
queries run in O(1) time in average.For the following binary search tree, in-order traversal by using iterator is [1, 6, 10, 11, 12]
10
/ 1 11
\ 6 12
Extra memory usage O(h), h is the height of the tree.
Super Star: Extra memory usage O(1)
Analyse: Recursion.
Runtime: 25ms
1 /** 2 * Definition of TreeNode: 3 * class TreeNode { 4 * public: 5 * int val; 6 * TreeNode *left, *right; 7 * TreeNode(int val) { 8 * this->val = val; 9 * this->left = this->right = NULL; 10 * } 11 * } 12 * Example of iterate a tree: 13 * BSTIterator iterator = BSTIterator(root); 14 * while (iterator.hasNext()) { 15 * TreeNode * node = iterator.next(); 16 * do something for node 17 */ 18 class BSTIterator { 19 public: 20 //@param root: The root of binary tree. 21 BSTIterator(TreeNode *root) { 22 // write your code here 23 inorder = inorderTraversal(root); 24 index = 0; 25 } 26 27 //@return: True if there has next node, or false 28 bool hasNext() { 29 // write your code here 30 return index < inorder.size(); 31 } 32 33 //@return: return next node 34 TreeNode* next() { 35 // write your code here 36 if (index >= inorder.size()) return NULL; 37 return inorder[index++]; 38 } 39 40 private: 41 vector<TreeNode* > inorder; 42 int index; 43 44 vector<TreeNode* > inorderTraversal(TreeNode* root) { 45 vector<TreeNode* > result; 46 47 helper(result, root); 48 return result; 49 } 50 51 void helper(vector<TreeNode* >& result, TreeNode* root) { 52 if (!root) return; 53 54 helper(result, root->left); 55 result.push_back(root); 56 helper(result, root->right); 57 } 58 };
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/5851559.html