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