[LeetCode] 173. Binary Search Tree Iterator

Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):

  • BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
  • boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
  • int next() Moves the pointer to the right, then returns the number at the pointer.

Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.

You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.

Example 1:

Input
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
Output
[null, 3, 7, true, 9, true, 15, true, 20, false]

Explanation
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next();    // return 3
bSTIterator.next();    // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 20
bSTIterator.hasNext(); // return False

Constraints:

  • The number of nodes in the tree is in the range [1, 105].
  • 0 <= Node.val <= 106
  • At most 105 calls will be made to hasNext, and next.

Follow up:

  • Could you implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree?

二叉搜索树迭代器。

实现一个二叉搜索树迭代器类BSTIterator ,表示一个按中序遍历二叉搜索树(BST)的迭代器:
BSTIterator(TreeNode root) 初始化 BSTIterator 类的一个对象。BST 的根节点 root 会作为构造函数的一部分给出。指针应初始化为一个不存在于 BST 中的数字,且该数字小于 BST 中的任何元素。
boolean hasNext() 如果向指针右侧遍历存在数字,则返回 true ;否则返回 false 。
int next()将指针向右移动,然后返回指针处的数字。
注意,指针初始化为一个不存在于 BST 中的数字,所以对 next() 的首次调用将返回 BST 中的最小元素。

你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 的中序遍历中至少存在一个下一个数字。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-search-tree-iterator
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路很简单,就是实现树的中序遍历,参考94题。二叉搜索树的中序遍历正好是一个递增的序列。所以实现next()函数的时候,要创建一个stack然后按照中序遍历的思路将节点全都塞进stack,弹出的下一个节点即是next。判断是否有下一个节点的函数hasNext()的方法则是判断当前节点是否为空或者判断stack是否为空。

时间O(1) - 题目要求

空间O(h) - 题目要求

Java实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class BSTIterator {
11     private TreeNode cur;
12     private Stack<TreeNode> stack;
13 
14     public BSTIterator(TreeNode root) {
15         cur = root;
16         stack = new Stack<>();
17     }
18 
19     /** @return the next smallest number */
20     public int next() {
21         while (cur != null) {
22             stack.push(cur);
23             cur = cur.left;
24         }
25         cur = stack.pop();
26         int val = cur.val;
27         cur = cur.right;
28         return val;
29     }
30 
31     /** @return whether we have a next smallest number */
32     public boolean hasNext() {
33         if (!stack.isEmpty() || cur != null) {
34             return true;
35         }
36         return false;
37     }
38 }
39 
40 /**
41  * Your BSTIterator object will be instantiated and called as such:
42  * BSTIterator obj = new BSTIterator(root);
43  * int param_1 = obj.next();
44  * boolean param_2 = obj.hasNext();
45  */

 

JavaScript实现

 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeNode} root
10  */
11 var BSTIterator = function (root) {
12     let sort = [];
13     let dfs = function (root) {
14         if (!root) return;
15         dfs(root.left);
16         sort.push(root.val);
17         dfs(root.right);
18     }
19     dfs(root);
20     this.nodes = sort;
21     this.index = -1;
22 };
23 
24 /**
25  * @return the next smallest number
26  * @return {number}
27  */
28 BSTIterator.prototype.next = function () {
29     this.index++;
30     return this.nodes[this.index];
31 };
32 
33 /**
34  * @return whether we have a next smallest number
35  * @return {boolean}
36  */
37 BSTIterator.prototype.hasNext = function () {
38     return this.nodes[this.index + 1] != null;
39 };
40 
41 /** 
42  * Your BSTIterator object will be instantiated and called as such:
43  * var obj = new BSTIterator(root)
44  * var param_1 = obj.next()
45  * var param_2 = obj.hasNext()
46  */

 

相关题目

173. Binary Search Tree Iterator

1586. Binary Search Tree Iterator II

LeetCode 题目总结

posted @ 2020-03-11 08:23  CNoodle  阅读(433)  评论(0编辑  收藏  举报