String to two fork tree Leetcode C + + implementation

Source: Internet
Author: User

struct TreeNode {int val;    Treenode* left;    treenode* right; explicit TreeNode (int x): Val (x), left (nullptr), right (nullptr) {}};void trimlefttrailingspaces (string &input) {i    Nput.erase (Input.begin (), Find_if (Input.begin (), Input.end (), [] (int ch) {return!isspace (CH); }));}        void Trimrighttrailingspaces (String &input) {input.erase (find_if (Input.rbegin (), Input.rend (), [] (int ch) {    return!isspace (CH); }). Base (), Input.end ());}    treenode* stringtotreenode (String input) {trimlefttrailingspaces (input);    Trimrighttrailingspaces (input);    input = Input.substr (1, Input.length ()-2);    if (Input.empty ()) {return nullptr;    } string Item;    StringStream SS;    SS.STR (input);    Getline (SS, Item, ', ');    Auto root = new TreeNode (Stoi (item));    Queue<treenode*> Nodequeue;    Nodequeue.push (root);        while (true) {treenode* node = Nodequeue.front ();        Nodequeue.pop ();     if (!getline (SS, Item, ', ')) {       Break        } trimlefttrailingspaces (item);            if (item! = "NULL") {int leftnumber = Stoi (item);            Node->left = new TreeNode (leftnumber);        Nodequeue.push (Node->left);        } if (!getline (SS, Item, ', ')) {break;        } trimlefttrailingspaces (item);            if (item! = "NULL") {int rightnumber = Stoi (item);            Node->right = new TreeNode (rightnumber);        Nodequeue.push (Node->right); }} return root;}    void Pre_order (treenode* root) {if (root = = nullptr) return;    cout << root->val << ",";    Pre_order (Root->left); Pre_order (root->right);}

String to two fork tree Leetcode C + + implementation

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.