Squeezed 6-line C++ solution with stringstream and upper_bound (for fun)


  • 0

    Same as many posted solutions with upper_bound or lower_bound calls to get the starting position of right sub-tree node, so we can recursively build the original tree based on pre-order node values.

    public:
        string serialize(TreeNode* r) {
          return r? to_string(r->val) + " " + serialize(r->left) + " " + serialize(r->right) : "";
        }
        
        TreeNode* deserialize(string data) {
          vector<int> vals; int v;
          for (stringstream ss(data); ss >> v; vals.push_back(v)) ;
          return buildTree(vals.begin(), vals.end());
        }
        
    private:    
        TreeNode* buildTree(vector<int>::iterator s, vector<int>::iterator e) {
          auto r = e-s? new TreeNode(*s) : NULL; auto i = e-s? upper_bound(s+1,e,*s) : e;
          return r? r->left=buildTree(s+1,i), r->right=buildTree(i, e), r : r;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.