Practice/Meta/Leetcode 173. Binary Search Tree Iterator
CodingMust
Design and implement an iterator class for a Binary Search Tree (BST) that allows sequential traversal of the tree's values in sorted (ascending) order. Your iterator should support two operations:
next(): Returns the next smallest number in the BSThasNext(): Returns whether there are more elements to iterate overThe iterator should be initialized with the root node of a BST. When constructed, it should position itself before the first element, so that the first call to next() returns the smallest element in the tree.
BSTIterator class with a constructor that takes the root of a BSTnext() to return the next smallest element in the treehasNext() to return true if there are more elements, false otherwise[1, 10^5]0 <= Node.val <= 10^610^5 calls will be made to hasNext and nextnext() will be valid (when there are elements remaining)next() and hasNext() should run in average O(1) time with O(h) space, where h is the height of the treeExample 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(); // returns 3 bSTIterator.next(); // returns 7 bSTIterator.hasNext(); // returns true bSTIterator.next(); // returns 9 bSTIterator.hasNext(); // returns true bSTIterator.next(); // returns 15 bSTIterator.hasNext(); // returns true bSTIterator.next(); // returns 20 bSTIterator.hasNext(); // returns false `
Example 2:
` Input: ["BSTIterator", "next", "hasNext"] [[[1]], [], []]
Output: [null, 1, false]
Explanation: A single-node tree returns its value on first next(), then hasNext() is false. `