0
点赞
收藏
分享

微信扫一扫

<leetcode>606.根据二叉树创建字符串——树、迭代、递归

你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。

空节点则用一对空括号 “()” 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。

解答:递归

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void helper(TreeNode* root, string& res){
        if(root == nullptr) return;
        res += to_string(root->val);
        if(root->left != nullptr||root->right != nullptr){
            res += "(";
            helper(root->left, res);
            res += ")";
        }
        
        if(root->right != nullptr){
            res += "(";
            helper(root->right, res);
            res += ")";
        }
        
        
    }

    string tree2str(TreeNode* root) {
        string res;
        helper(root, res);
        return res;

    }
};
举报

相关推荐

0 条评论