[leetcode]606. Construct String from Binary Tree

[leetcode]606. Construct String from Binary Tree


Analysis

ummm~—— [ummmm~]

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair “()”. And you need to omit all the empty parenthesis pairs that don’t affect the one-to-one mapping relationship between the string and the original binary tree.
递归解决,然后需要注意的是关于空括号的忽略问题,右子树为空时产生的空括号可以忽略,左子树为空时产生的空括号不可以忽略。因为左子树的空括号忽略后悔使字符串中原来的右子树变成左子树。

Implement

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

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/81006981