반응형
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
전위순회하며 재귀적으로 풀 수 있었습니다.
좌측 노드가 없더라도 우측 노드가 있으면 빈 괄호를 넣어줍니다.
class Solution {
public:
string tree2str(TreeNode* root) {
string str = to_string(root->val);
if(root->left) {
str += "(" + tree2str(root->left) + ")";
} else {
if(root->right) {
str += "()";
}
}
if(root->right) {
str += "(" + tree2str(root->right) + ")";
}
return str;
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 867. Transpose Matrix (1) | 2023.12.10 |
---|---|
LeetCode 94. Binary Tree Inorder Traversal (0) | 2023.12.09 |
LeetCode 1903. Largest Odd Number in String (1) | 2023.12.07 |
LeetCode 1716. Calculate Money in Leetcode Bank (1) | 2023.12.07 |
LeetCode 1688. Count of Matches in Tournament (0) | 2023.12.06 |