C++ easy real preorder solution


  • 0
    M
        string tree2str(TreeNode* t) {
            if(t==NULL) return "";
            string res=to_string(t->val);
            if(t->left!=NULL||t->right!=NULL) pre(t->left, res);
            if(t->right!=NULL) pre(t->right, res);
            return res;
        }
        
        void pre(TreeNode* r, string& res) {
            res+="(";
            if(r!=NULL) {
                res+=to_string(r->val);
                if(r->left!=NULL||r->right!=NULL) pre(r->left, res);
                if(r->right!=NULL) pre(r->right, res);
            }
            res+=")";
        }

Log in to reply
 

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