Construct String from Binary Tree

ㅋㅋ·2022년 9월 7일
0

알고리즘-leetcode

목록 보기
37/135

트리가 주어지고 트리를 순회하며 트리의 값들을 괄호로 묶어 스트링으로 반환하는 문제

트리가 널일 경우 괄호를 생략해도 되는데,

이 때 왼쪽 자식 트리는 널인데 오른쪽 자식 트리는 값이 존재할 경우는 괄호를 생략하면 안된다.

/**
 * 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) {
        
        if (root == NULL)
        {
            return {""};
        }
        
        string result{""};
        
        result += to_string(root->val);
        
        if (root->left)
        {
            result += '(';
            result += tree2str(root->left);
            result += ')';
        }
        
        if (root->right)
        {
            if (root->left == NULL)
            {
                result += "()(";
            }
            else
            {
                result += '(';
            }
            
            result += tree2str(root->right);
            result += ')';
        }
        
        return result;
    }
};

0개의 댓글