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:
    string tree2str(TreeNode* root) {
        string str = to_string(root -> val);
        if(root -> left != NULL || root -> right != NULL) {
            str += (root -> left == NULL ? "()" : '(' + tree2str(root -> left) + ')') + (root -> right == NULL ? "" : '(' + tree2str(root -> right) + ')');
        }
        return str;
    }
};

你可能感兴趣的:(刷题,leetcode,算法,c++,数据结构,dfs)