Binary Search Tree Iterator Solution

Source: Internet
Author: User

Question

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() hasNext() and should run in average O (1) time and uses O (h) memory, where H is the height of the Tree.

Solution

When a problem relates to BST and sequence, we should think about in-order traversal of BST.

We find that the original codes of Binary Tree inorder traversal can is modified to fit following codes.

 while (It.hasnext ()) {    System.out.println (It.next ());        }

Note that before print, we need to the push nodes to stack first.

Inorder traversal time complexity is O (n), so for each next () step, average Time is O (1).

And the stack costs O (h) because we either goes down or pops a node and then goes down.

1 /**2 * Definition for binary tree3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8  * }9  */Ten  One  Public classBstiterator { A     PrivateStack<treenode>Stack; -     PrivateTreeNode Current; -  the      Publicbstiterator (TreeNode root) { -stack =NewStack<treenode>(); -Current =Root; -          while(Current! =NULL) { + Stack.push (current); -Current =Current.left; +         } A          at     } -  -     /** @returnwhether we have a next smallest number*/ -      Public BooleanHasnext () { -         return(! Stack.empty () | | | current! =NULL); -     } in  -     /** @returnThe next smallest number*/ to      Public intNext () { +          while(Current! =NULL) { - Stack.push (current); theCurrent =Current.left; *         } $TreeNode tmp =Stack.pop ();Panax Notoginseng         intresult =Tmp.val; -Current =Tmp.right; the         returnresult; +     } A } the  + /** - * Your Bstiterator 'll be a called like this: $ * Bstiterator i = new Bstiterator (root); $ * while (I.hasnext ()) v[f ()] = I.next (); -  */

Binary Search Tree Iterator Solution

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.