LeetCode - Construct String from Binary Tree

/**
 * 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 tree2str(TreeNode* t) {
        if(!t) return "";
        string left = tree2str(t->left);
        string right = tree2str(t->right);
        if(left==""&&right=="") return to_string(t->val);
        if(right==""){
            return to_string(t->val)+"("+left+")";
        }else{
            return to_string(t->val)+"("+left+")"+"("+right+")";
        }
    }
};

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/83060643