Skip to content

Commit 1c55fcf

Browse files
committed
added Q606
1 parent 03fac0c commit 1c55fcf

File tree

1 file changed

+130
-0
lines changed

1 file changed

+130
-0
lines changed
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
---
2+
id: construct-string-from-binary-tree
3+
title: Construct String from Binary Tree
4+
sidebar_label: 0606-Construct-String-from-Binary-Tree
5+
tags:
6+
- Tree
7+
- Depth-First Search
8+
- Binary Tree
9+
description: "Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way."
10+
---
11+
12+
## Problem
13+
14+
Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way.
15+
16+
### Examples
17+
18+
**Example 1:**
19+
20+
**Input:** `root = [1,2,3,4]`
21+
**Output:** `"1(2(4))(3)"`
22+
**Explanation:** Originally, it needs to be `"1(2(4)())(3()())"`, but you need to omit all the unnecessary empty parenthesis pairs. And it will be `"1(2(4))(3)"`
23+
24+
**Example 2:**
25+
26+
**Input:** `root = [1,2,3,null,4]`
27+
**Output:** `"1(2()(4))(3)"`
28+
**Explanation:** Originally, it needs to be `"1(2()(4)())(3()())"`, but you need to omit all the unnecessary empty parenthesis pairs. And it will be `"1(2()(4))(3)"`
29+
30+
### Constraints
31+
32+
- The number of nodes in the tree is in the range `[1, 10^4]`.
33+
- `-5000 <= Node.val <= 5000`
34+
35+
---
36+
37+
## Approach
38+
39+
To construct the string from the binary tree with the preorder traversal, we need to follow these steps:
40+
41+
1. If the current node is `null`, return an empty string.
42+
2. Add the value of the current node to the result string.
43+
3. If the left child is `null` but the right child is not `null`, add `()` to represent the left child.
44+
4. Recursively add the left child string.
45+
5. Recursively add the right child string if it exists.
46+
47+
### Solution
48+
49+
#### Java Solution
50+
51+
```java
52+
public class TreeNode {
53+
int val;
54+
TreeNode left;
55+
TreeNode right;
56+
TreeNode(int x) { val = x; }
57+
}
58+
59+
class Solution {
60+
public String tree2str(TreeNode root) {
61+
if (root == null) return "";
62+
String result = Integer.toString(root.val);
63+
if (root.left != null || root.right != null) {
64+
result += "(" + tree2str(root.left) + ")";
65+
if (root.right != null) {
66+
result += "(" + tree2str(root.right) + ")";
67+
}
68+
}
69+
return result;
70+
}
71+
}
72+
```
73+
#### C++ Solution
74+
75+
```cpp
76+
#include <string>
77+
using namespace std;
78+
79+
struct TreeNode {
80+
int val;
81+
TreeNode *left;
82+
TreeNode *right;
83+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
84+
};
85+
86+
class Solution {
87+
public:
88+
string tree2str(TreeNode* root) {
89+
if (!root) return "";
90+
string result = to_string(root->val);
91+
if (root->left || root->right) {
92+
result += "(" + tree2str(root->left) + ")";
93+
if (root->right) {
94+
result += "(" + tree2str(root->right) + ")";
95+
}
96+
}
97+
return result;
98+
}
99+
};
100+
```
101+
#### Python Solution
102+
103+
```python
104+
# Definition for a binary tree node.
105+
class TreeNode:
106+
def __init__(self, val=0, left=None, right=None):
107+
self.val = val
108+
self.left = left
109+
self.right = right
110+
111+
class Solution:
112+
def tree2str(self, root: TreeNode) -> str:
113+
if not root:
114+
return ""
115+
result = str(root.val)
116+
if root.left or root.right:
117+
result += f"({self.tree2str(root.left)})"
118+
if root.right:
119+
result += f"({self.tree2str(root.right)})"
120+
return result
121+
```
122+
### Complexity Analysis
123+
**Time Complexity:** O(n)
124+
>Reason: Each node is visited once during the traversal.
125+
126+
**Space Complexity:** O(h)
127+
>Reason: The space complexity is determined by the recursion stack, which in the worst case (unbalanced tree) is O(n), but on average (balanced tree) is O(log n).
128+
129+
### References
130+
**LeetCode Problem:** Construct String from Binary Tree

0 commit comments

Comments
 (0)