Leetcode[tree]: 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 next () would return the next smallest number in the 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.

Reference: Https://oj.leetcode.com/discuss/20001/my-solutions-in-3-languages-with-stack

Solution idea: Save all Left children starting from the root node with a stack, each time invoking Next () pops an element from the stack, and will repeat the same process with the right child of the node as the subtree of the root node.

The algorithm satisfies the spatial complexity of O (h) and the time complexity of hasnext () satisfies O (1), although the time complexity of next () is O (h), but the process of the algorithm is still worth learning.

The C + + code is implemented as follows:

/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */Class Bstiterator {Private: Stack<treenode *> Nodestack;voidPushall (TreeNode *root) { for(TreeNode *node = root; Node! = nullptr; node = node->left)        {Nodestack.push (node); }    } Public:Bstiterator(TreeNode *root)    {Pushall (root); }/** @return Whether we have a next smallest number * /BOOL Hasnext () {return!nodestack.empty (); }/** @return the next smallest number * *    intNext () {TreeNode *node = Nodestack.top ();        Nodestack.pop (); Pushall (Node->right);returnnode->val; }};/** * Your Bstiterator'll be a called like this: * bstiterator i = bstiterator (root), * while (I.hasnext ()) cout <& Lt I.next (); */

The time performance of the algorithm is as follows:

Leetcode[tree]: 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.