[java]leetcode173 Binary Search Tree Iterator

Source: Internet
Author: User

Implement an iterator over a binary search tree (BST). Your iterator is initialized with the root node of a BST.

Calling would return the next smallest number in the next() 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.

Test instructions: Write a binary lookup tree iterator that implements the functions of Hasnext () and Next (). Next () returns the minimum value that is not accessed in the binary tree each time. The average time complexity required is O (1) and the spatial complexity is O (h).

Problem solving: Next () returns the minimum value that is not accessed in the binary tree each time. That is, the two-fork tree is traversed in sequence and the corresponding value is output. This is about the complexity of space and time.

The public class Bstiterator {//Will embed the function of the middle sequence traversal in the entire program    TreeNode current;    stack<treenode> Stack;    Public bstiterator (TreeNode root) {        current=root;        Stack=new stack<treenode> ();        while (Current!=null)//Because only the left node is the minimum value, all the left subtree nodes are put into the stack, ensuring that the spatial complexity is O (h)        {            Stack.push (current);            Current=current.left;        }    }    /** @return Whether we have a next smallest number *    /public boolean hasnext () {     return!stack.isempty ();    }    /** @return The next smallest number *    /public int next () {      current=stack.pop ();      int res=current.val;//This step has been given a minimum value      current=current.right;//but take into account the right subtree traversal while      (Current!=null)       {         Stack.push (current);         Current=current.left;       }       return res;      }}


[java]leetcode173 Binary Search Tree Iterator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.