-
[LeetCode] 606.Construct String from Binary TreeLeetCode 2023. 12. 8. 13:32728x90
https://leetcode.com/problems/construct-string-from-binary-tree
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
606.Construct String from Binary Tree - Easy


Binary tree 가 주어졌을때, 이를 node value와 괄호를 이용해 string으로 나타내는 문제다.
주의점은, left만 있고 right가 없을땐 left만 출력하고, right만 있을때는 left는 빈괄호를 써줘야한다.
left부터 나오고, right보다도 left의 자식들이 먼저 나오므로 DFS를 써주면 된다.
class Solution { public: string run(TreeNode* t) { if(!t) return ""; string r = to_string(t->val); if (t->left || t->right) r += "(" + run(t->left) + ")"; if (t->right) r += "(" + run(t->right) + ")"; return r; } string tree2str(TreeNode* t) {return run(t);} };'LeetCode' 카테고리의 다른 글
[LeetCode] 1662. Check If Two String Arrays are Equivalent (0) 2023.12.01 [LeetCode] 1611. Minimum One Bit Operations to Make Integers Zero (1) 2023.11.30 [LeetCode] 695. Max Area of Island (2) 2023.11.29 [LeetCode] 2147. Number of Ways to Divide a long Corridor (1) 2023.11.28 [LeetCode] 557. Reverse Words in a String III (0) 2023.11.27