넘치게 채우기

[LeetCode] 606. Construct String from Binary Tree 본문

PS/LeetCode

[LeetCode] 606. Construct String from Binary Tree

riveroverflow 2023. 12. 8. 11:13
728x90
반응형

https://leetcode.com/problems/construct-string-from-binary-tree/description/

 

Construct String from Binary Tree - LeetCode

Can you solve this real interview question? Construct String from Binary Tree - 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

leetcode.com

leetcode - Construct String from Binary Tree

문제 유형 : 순회 / DFS / 재귀 / 탐색

문제 난이도 : Easy

 

문제

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.

 

이진 트리의 루트가 주어진다. 전위 순회를 한 형태로 트리의 요소들을 한 문자열로 묶어 반환하시오.

루트(왼쪽서브트리)(오른쪽서브트리)의 형태로 반환하시오.

문자열과 원래 이진트리 간의 일대일 매핑 관계에 영향을 주지 않는 모든 빈 관호쌍은 생략합니다.

 

풀이

간단히 전위 순회를 하면서 문자열을 생성하면 된다.

루트(왼쪽서브트리)(오른쪽서브트리)

단, 왼쪽 서브트리가 없고, 오른쪽 서브트리가 존재하는 경우에는 왼쪽 서브트리 부분은 빈 괄호쌍으로 대체한다.

다른 자식노드들이 없는 경우는 그냥 만든지 않으면 된다.

 

 

코드

C++

/**
 * 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) {}
 * };
 */

 static const int __ = []() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    return 0;
 }();

class Solution {
public:
    string prefix_traversal(TreeNode* root) {
        if(root == nullptr) return "";
        string left = "";
        string right = "";
        if(root -> left || root -> right) {
            left = "(" + prefix_traversal(root -> left) + ")";
        }
        if(root -> right) {
            right = "(" + prefix_traversal(root -> right) + ")";
        }
        return to_string(root -> val) + left + right;
    }
    string tree2str(TreeNode* root) {
        return prefix_traversal(root);
    }
};

 

728x90
반응형