Leetcode : Binary Search Tree Iterator
2015-04-13 21:53
127 查看
题目描述
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.
思想:
中序遍历的拆分。用栈保存路径,但是并非一次性遍历所有的节点,不然存储空间太大。每次只保存左侧节点到最底层节点。
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.
思想:
中序遍历的拆分。用栈保存路径,但是并非一次性遍历所有的节点,不然存储空间太大。每次只保存左侧节点到最底层节点。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class BSTIterator { public: BSTIterator(TreeNode *root) { TreeNode *p = root; while(p)//左节点不断入栈,相当于寻找中序遍历的第一个元素 { temp.push(p); p = p->left; } } /** @return whether we have a next smallest number */ bool hasNext() { return !temp.empty(); } /** @return the next smallest number */ int next() { TreeNode *q = temp.top(); int x = q->val; temp.pop(); q=q->right; while(q)//继续把右节点的左侧遍历入栈 { temp.push(q); q = q->left; } return x; } private: stack<TreeNode *> temp; }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
相关文章推荐
- LeetCode Binary Search Tree Iterator
- Leetcode: Binary Search Tree Iterator
- LeetCode173-Binary Search Tree Iterator
- Leetcode: Binary Search Tree Iterator
- 173.leetcode Binary Search Tree Iterator(medium)[二叉搜索树 栈 中序遍历]
- Leetcode Binary Search Tree Iterator
- LeetCode[Tree]: Binary Search Tree Iterator
- 8.10 [LeetCode 173] Binary Search Tree Iterator
- Leetcode: Binary Search Tree Iterator
- [LeetCode] Binary Search Tree Iterator
- LeetCode Binary Search Tree Iterator
- leetcode之Binary Search Tree Iterator
- 开始刷leetcode day78:Binary Search Tree Iterator
- leetcode Binary Search Tree Iterator python
- Leetcode: Binary Search Tree Iterator
- Leetcode Binary Search Tree Iterator
- LeetCode - 173 - Binary Search Tree Iterator
- LeetCode - 173 - Binary Search Tree Iterator
- LeetCode OJ Binary Search Tree Iterator
- [leetcode]Binary Search Tree Iterator