Binary Search Tree Iterator

Source: Internet
Author: User

Design an iterator-a binary search tree with the following rules:

    • Elements is visited in ascending order (i.e. an in-order traversal)
    • next()and hasNext() queries run in O (1) time in average.
Example

For the following binary search tree, In-order traversal by using iterator are[1, 6, 10, 11, 12]

   10 /    1      11 \         6       12
Challenge

Extra Memory Usage O (h), H is the height of the tree.

Super Star: Extra Memory usage O (1)

Analyse:recursion.

Runtime:25ms

1 /**2 * Definition of TreeNode:3 * Class TreeNode {4 * Public:5 * int val;6 * TreeNode *left, *right;7 * TreeNode (int val) {8 * This->val = val;9 * This->left = This->right = NULL;Ten  *     } One  * } A * Example of iterate a tree: - * Bstiterator iterator = bstiterator (root); - * while (Iterator.hasnext ()) { the * TreeNode * node = Iterator.next (); - * Do something for node -  */ - classBstiterator { +  Public: -     //@param root:the root of binary tree. +Bstiterator (TreeNode *root) { A         //Write your code here atInorder =inordertraversal (root); -index =0; -     } -  -     //@return: True If there has next node, or false -     BOOLHasnext () { in         //Write your code here -         returnIndex <inorder.size (); to     } +      -     //@return: Return to next node thetreenode*Next () { *         //Write your code here $         if(Index >= inorder.size ())returnNULL;Panax Notoginseng         returninorder[index++]; -     } the      + Private: Avector<treenode* >inorder; the     intindex; +      -vector<treenode* > Inordertraversal (treenode*root) { $vector<treenode* >result; $          - Helper (result, root); -         returnresult; the     } -     Wuyi     voidHelper (vector<treenode* >& result, treenode*root) { the         if(!root)return; -          WuHelper (result, root->Left ); - Result.push_back (root); AboutHelper (result, root->Right ); $     } -};

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.