[leetcode] 173. Binary Search Tree Iterator
2016-05-20 20:58
369 查看
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling
Note:
run in average O(1) time and uses O(h) memory, where h is the height of the tree.
这道题是实现BST迭代器,题目难度为Medium。
BST相信大家都熟悉,就不详细介绍了。根据BST的特点,中序遍历BST即得到节点值从小到大排列的所有节点。next()函数找下一个最小值节点,即中序遍历的下一节点,从根节点开始,一直向左子树遍历,直到遍历到左子树为空的节点为止,此时的节点即是初始的最小值节点,遍历此节点,之后跳转到它的右子树(如果不为空)继续遍历,在遍历完右子树之后,以此节点为根的子树就遍历完了,此时要跳转到它的父节点继续遍历,所以这里需要借助栈来存储遍历路径上的所有节点以便回退时使用,即中序遍历二叉树的思路。
题目限定时间复杂度O(1),空间复杂度O(h),所以构造函数要将栈中数据预先准备好,以便next()函数返回栈顶元素;hasNext()函数判断栈是否为空即可;next()函数在出栈返回最小值之后,要跳转到最小值节点的右子树继续中序遍历的相应操作。具体代码:
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.
这道题是实现BST迭代器,题目难度为Medium。
BST相信大家都熟悉,就不详细介绍了。根据BST的特点,中序遍历BST即得到节点值从小到大排列的所有节点。next()函数找下一个最小值节点,即中序遍历的下一节点,从根节点开始,一直向左子树遍历,直到遍历到左子树为空的节点为止,此时的节点即是初始的最小值节点,遍历此节点,之后跳转到它的右子树(如果不为空)继续遍历,在遍历完右子树之后,以此节点为根的子树就遍历完了,此时要跳转到它的父节点继续遍历,所以这里需要借助栈来存储遍历路径上的所有节点以便回退时使用,即中序遍历二叉树的思路。
题目限定时间复杂度O(1),空间复杂度O(h),所以构造函数要将栈中数据预先准备好,以便next()函数返回栈顶元素;hasNext()函数判断栈是否为空即可;next()函数在出栈返回最小值之后,要跳转到最小值节点的右子树继续中序遍历的相应操作。具体代码:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class BSTIterator { stack<TreeNode*> stk; public: BSTIterator(TreeNode *root) { while(root) { stk.push(root); root = root->left; } } /** @return whether we have a next smallest number */ bool hasNext() { return !stk.empty(); } /** @return the next smallest number */ int next() { TreeNode* n = stk.top(); int ret = n->val; stk.pop(); n = n->right; while(n) { stk.push(n); n = n->left; } return ret; } }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */空间复杂度O(h)达到了,hasNext()函数的时间复杂度O(1)也达到了,next()函数至多调用节点个数次,而栈的入栈和出栈最多也是节点个数次,所以next()函数的平均时间复杂度也是O(1)。
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解