Binary Search Tree Iterator

Source: Internet
Author: User

At first, I didn't know what the problem meant, and it was easy to know what he meant to say.

Idea: Find the minimum value, you can refer to the middle sequence traversal, with the help of stacks! Each element pops up, adding elements to the stack without having to traverse the entire tree immediately!

/** * Definition for binary tree * struct TreeNode {*     int val; *     TreeNode *left; *     TreeNode *right; *     Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class bstiterator {private:    stack<treenode*> stk;public:    bstiterator (TreeNode *root) {while        ( Root)        {            stk.push (root);            root=root->left;        }    }    /** @return Whether we have a next smallest number *    /bool Hasnext () {        return!stk.empty ();    }    /** @return The next smallest number */    int Next () {        treenode*temp=stk.top ();        Stk.pop ();        int res=temp->val;        temp=temp->right;        while (temp)        {            Stk.push (temp);            temp=temp->left;        }        return res;    }};/ * * Your Bstiterator'll be a called like this: * bstiterator i = bstiterator (root); * while (I.hasnext ()) cout << i.next (); */

  

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.