Binary Search Tree Iterator

Source: Internet
Author: User

https://oj.leetcode.com/problems/binary-search-tree-iterator/

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.

Problem Solving Ideas:

The first thing you have to know is, what is binary seach tree? It is a binary tree that is easy to search for. Similar to the idea of binary lookup, all nodes of the left subtree of BST are "= parent node, all nodes of right subtree" = parent node, which is also true for each subtree of the parent node. This is a recursive definition.

Also know that a single BST is sorted out, that is, it is on the line in sequence traversal. Why? Sort output is from small to large output, of course, the first output of the left subtree, and then in their own, and then the right sub-tree. That is, the middle sequence traversal.

The topic requires next () a Hasnext () method to have an O (1) time complexity, which is constant. In general, either using an array, you can get the value directly from the subscript, or use HashMap. Then it means we have to save these values as well.

According to this idea, a pre-declaration of a queue, used to save the results of the sequence traversal. Then just output it in the order of the queue. When the queue is empty, Hasnext returns false.

Here I use the iterative method to do the middle sequence traversal, with recursion can also. This iteration is written in very many interviews will require writing, Bugfree, is very important.

/*** Definition for Binary tree * public class TreeNode {* Int. val; * TreeNode left; * TreeNode right; * TreeNode (int x) {val = x;} }*/ Public classBstiterator {PrivateTreeNode Root; PrivateStack<treenode>Stack; PrivateLinkedlist<integer>vallist;  Publicbstiterator (TreeNode root) { This. root =Root; Stack=NewStack<treenode>(); Vallist=NewLinkedlist<integer>(); //Stack.push (root); //conditions are important .         while(Stack.size ()! = 0 | | Root! =NULL){            if(Root! =NULL) {Stack.push (root); Root=Root.left; }Else{                if(Stack.size () > 0) {root=Stack.pop ();                    Vallist.offer (Root.val); Root=Root.right; }            }        }    }    /** @returnwhether we have a next smallest number*/     Public BooleanHasnext () {if(Vallist.size () > 0){            return true; }Else{            return false; }    }    /** @returnThe next smallest number*/     Public intNext () {returnVallist.poll (); }}/*** Your Bstiterator'll be a called like this: * bstiterator i = new Bstiterator (root), * while (I.hasnext ()) v[f ()] = I.next (); */

But looking at the topic, the next and Hasnext methods are O (1), but this queue costs O (n) of memory. The topic requires the cost O (h), h as the depth, i.e. O (logn). That means you can't do it. Think again.

Then I can only use a data structure, not the previous queue, the elements stored in it, only the height of the tree is related to the linear. If you want to go, you can only use inorder to traverse the stack in the middle itself.

Using this method to do, in fact, is the above In-order recursive method to write separately. The bottom note also gives a way for users to call next and Hasnext, and check hasnext before each call to next. The code is as follows.

/*** Definition for Binary tree * public class TreeNode {* Int. val; * TreeNode left; * TreeNode right; * TreeNode (int x) {val = x;} }*/ Public classBstiterator {PrivateTreeNode Root; PrivateStack<treenode>Stack;  Publicbstiterator (TreeNode root) { This. root =Root; Stack=NewStack<treenode>(); }    /** @returnwhether we have a next smallest number*/     Public BooleanHasnext () { while(Root! =NULL) {Stack.push (root); Root=Root.left; }        if(Stack.size () > 0){            return true; }Else{            return false; }    }    /** @returnThe next smallest number*/     Public intNext () {root=Stack.pop (); intReturnValue =Root.val; Root=Root.right; returnreturnvalue; }}/*** Your Bstiterator'll be a called like this: * bstiterator i = new Bstiterator (root), * while (I.hasnext ()) v[f ()] = I.next (); */

But this memory is O (h), Hasnext () can not reach O (1), perhaps the original problem is said to be average O (1), I do not know is not so, or say the best?

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.