Skip to content

Latest commit

 

History

History
129 lines (106 loc) · 3.98 KB

173. Binary Search Tree Iterator.md

File metadata and controls

129 lines (106 loc) · 3.98 KB

leetcode Daily Challenge on December 9th, 2020.


Difficulty : Medium

Related Topics : StackTreeDesign


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, 10^5].
  • 0 <= Node.val <= 10^6
  • At most 10^5 calls will be made to hasNext, and next.

Solution

  • mine
    • Java
      • DFS Runtime: 15 ms, faster than 90.21%, Memory Usage: 44.7 MB, less than 38.28% of Java online submissions
        // O(N)time O(N)space
        public LinkedList<Integer> list;
        public BSTIterator(TreeNode root) {
            list = new LinkedList<>();
            dfs(root,list);
        }
        
        public void dfs(TreeNode node, List<Integer> list){
            if(node == null){
                return;
            }
            dfs(node.left, list);
            list.add(node.val);
            dfs(node.right, list);
        }
        
        public int next() {
            return list.removeFirst();
        }
        
        public boolean hasNext() {
            return list.size() > 0;
        }
        

  • the most votes
    • Controlled Recursion Runtime: 15 ms, faster than 90.21%, Memory Usage: 44.3 MB, less than 85.79% of Java online submissions
      //O(D)time O(D)space
      // D is the root's deep
      LinkedList<TreeNode> stack;
      public BSTIterator(TreeNode root) {
      
          // Stack for the recursion simulation
          this.stack = new LinkedList<TreeNode>();
      
          // Remember that the algorithm starts with a call to the helper function
          // with the root node as the input
          this._leftmostInorder(root);
      }
      
      private void _leftmostInorder(TreeNode root) {
          while (root != null) {
              this.stack.push(root);
              root = root.left;
          }
      }
      
      public int next() {
          // Node at the top of the stack is the next smallest element
          TreeNode topmostNode = this.stack.pop();
      
          // Need to maintain the invariant. If the node has a right child, call the
          // helper function for the right child
          if (topmostNode.right != null) {
              this._leftmostInorder(topmostNode.right);
          }
      
          return topmostNode.val;
      }
      
      public boolean hasNext() {
          return this.stack.size() > 0;
      }