Leetcode——606. 根据二叉树创建字符串

题目传送门

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution 
{
public:
    string str;
    void midVisit(TreeNode* t)
    {
        if(t!=NULL)
        {
            str+="(";
            str+=to_string(t->val);
            if(t->left!=NULL&&t->right==NULL)
                midVisit(t->left);
            if(t->left==NULL&&t->right!=NULL)
            {
                str+="()";
                midVisit(t->right);
            }
            if(t->left!=NULL&&t->right!=NULL)
            {
                midVisit(t->left);
                midVisit(t->right);
            }
            str+=")";            
        }
    }
    string tree2str(TreeNode* t) 
    {
        if(t==NULL)
            return "";
        midVisit(t);
        return str.substr(1,str.length()-2);
    }
};

你可能感兴趣的:(leetcode)