Coding Test/LeetCode

[LeetCode] 606. Construct String from Binary Tree c++

owls 2022. 12. 24. 14:58
728x90
  • 문제

Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.

Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.

Input: root = [1,2,3,null,4]
Output: "1(2()(4))(3)"
Explanation: Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.

P (LC)(RC) 형태로 부모 노드와 연결된 자식노드들을 괄호로 표시하는 문제이다.

RC가 없다면 해당 괄호는 생략해도 된다 : P(LC) 

LC가 없다면 해당 괄호는 생략하면 안된다. P()(RC)

 

  • 문제 해결
/**
 * 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 {
private:
    void tree2str(TreeNode* curr, string& str){
        if(!curr){
            return;
        }
        str += to_string(curr->val);
        if(curr->left){
            str += '(';
            tree2str(curr->left, str);
            str += ')';
        }
        
        if(curr->right){
            if(!curr->left){
                str += "()";
             }
            str += '(';
            tree2str(curr->right, str);
            str += ')';
        }
        return;
    }
    
public:
    string tree2str(TreeNode* root) {
        string str("");
        tree2str(root, str);
        return str;
    }
};

 

728x90