Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9c282cc

Browse files
committed
feat: add solutions to lc problem: No.0655
No.0655.Print Binary Tree
1 parent 040351e commit 9c282cc

File tree

3 files changed

+466
-6
lines changed

3 files changed

+466
-6
lines changed

‎solution/0600-0699/0655.Print Binary Tree/README.md‎

Lines changed: 239 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,21 @@
5656

5757
<!-- 这里可写通用的实现逻辑 -->
5858

59-
> 中文题意不容易读懂,可以参考[英文版本的题目描述](/solution/0600-0699/0655.Print%20Binary%20Tree/README_EN.md)
59+
**方法一:两次 DFS**
6060

61-
先求二叉树的高度 h,然后根据 h 求得结果列表的行数和列数 m, n
61+
先通过 $DFS$ 求二叉树的高度 $h$(高度从 0ドル$ 开始),然后根据 $h$ 求得结果列表的行数 $m$ 和列数 $n$
6262

63-
根据 m, n 初始化结果列表,然后 dfs 遍历二叉树,依次在每个位置填入二叉树节点值(字符串形式)即可。
63+
根据 $m,ドル $n$ 初始化结果列表 $ans,ドル然后 $DFS$ 遍历二叉树,依次在每个位置填入二叉树节点值(字符串形式)即可。
64+
65+
时间复杂度 $O(h \times 2^h),ドル空间复杂度 $O(h)$。其中 $h$ 是二叉树的高度。忽略结果返回值的空间消耗。
66+
67+
**方法二:两次 BFS**
68+
69+
方法一中,我们是通过 $DFS$ 来求二叉树的高度,我们也可以改成 $BFS$ 的方式,逐层往下扩展,那么扩展的层数就是二叉树的高度。
70+
71+
同样,我们初始化结果列表 $ans,ドル然后 $BFS$ 遍历二叉树,依次在每个位置填入二叉树节点值(字符串形式)即可。
72+
73+
时间复杂度 $O(h \times 2^h),ドル空间复杂度 $O(h)$。其中 $h$ 是二叉树的高度。忽略结果返回值的空间消耗。
6474

6575
<!-- tabs:start -->
6676

@@ -76,7 +86,7 @@
7686
# self.left = left
7787
# self.right = right
7888
class Solution:
79-
def printTree(self, root: TreeNode) -> List[List[str]]:
89+
def printTree(self, root: Optional[TreeNode]) -> List[List[str]]:
8090
def height(root):
8191
if root is None:
8292
return -1
@@ -96,6 +106,42 @@ class Solution:
96106
return ans
97107
```
98108

109+
```python
110+
# Definition for a binary tree node.
111+
# class TreeNode:
112+
# def __init__(self, val=0, left=None, right=None):
113+
# self.val = val
114+
# self.left = left
115+
# self.right = right
116+
class Solution:
117+
def printTree(self, root: Optional[TreeNode]) -> List[List[str]]:
118+
def height(root):
119+
q = deque([root])
120+
h = -1
121+
while q:
122+
h += 1
123+
for _ in range(len(q)):
124+
root = q.popleft()
125+
if root.left:
126+
q.append(root.left)
127+
if root.right:
128+
q.append(root.right)
129+
return h
130+
131+
h = height(root)
132+
m, n = h + 1, 2 ** (h + 1) - 1
133+
ans = [[""] * n for _ in range(m)]
134+
q = deque([(root, 0, (n - 1) // 2)])
135+
while q:
136+
node, r, c = q.popleft()
137+
ans[r][c] = str(node.val)
138+
if node.left:
139+
q.append((node.left, r + 1, c - 2 ** (h - r - 1)))
140+
if node.right:
141+
q.append((node.right, r + 1, c + 2 ** (h - r - 1)))
142+
return ans
143+
```
144+
99145
### **Java**
100146

101147
<!-- 这里可写当前语言的特殊实现逻辑 -->
@@ -150,6 +196,84 @@ class Solution {
150196
}
151197
```
152198

199+
```java
200+
/**
201+
* Definition for a binary tree node.
202+
* public class TreeNode {
203+
* int val;
204+
* TreeNode left;
205+
* TreeNode right;
206+
* TreeNode() {}
207+
* TreeNode(int val) { this.val = val; }
208+
* TreeNode(int val, TreeNode left, TreeNode right) {
209+
* this.val = val;
210+
* this.left = left;
211+
* this.right = right;
212+
* }
213+
* }
214+
*/
215+
class Solution {
216+
public List<List<String>> printTree(TreeNode root) {
217+
int h = height(root);
218+
int m = h + 1, n = (1 << (h + 1)) - 1;
219+
String[][] res = new String[m][n];
220+
for (int i = 0; i < m; ++i) {
221+
Arrays.fill(res[i], "");
222+
}
223+
Deque<Tuple> q = new ArrayDeque<>();
224+
q.offer(new Tuple(root, 0, (n - 1) / 2));
225+
while (!q.isEmpty()) {
226+
Tuple p = q.pollFirst();
227+
root = p.node;
228+
int r = p.r, c = p.c;
229+
res[r][c] = String.valueOf(root.val);
230+
if (root.left != null) {
231+
q.offer(new Tuple(root.left, r + 1, c - (1 << (h - r - 1))));
232+
}
233+
if (root.right != null) {
234+
q.offer(new Tuple(root.right, r + 1, c + (1 << (h - r - 1))));
235+
}
236+
}
237+
List<List<String>> ans = new ArrayList<>();
238+
for (String[] t : res) {
239+
ans.add(Arrays.asList(t));
240+
}
241+
return ans;
242+
}
243+
244+
private int height(TreeNode root) {
245+
Deque<TreeNode> q = new ArrayDeque<>();
246+
q.offer(root);
247+
int h = -1;
248+
while (!q.isEmpty()) {
249+
++h;
250+
for (int n = q.size(); n > 0; --n) {
251+
root = q.pollFirst();
252+
if (root.left != null) {
253+
q.offer(root.left);
254+
}
255+
if (root.right != null) {
256+
q.offer(root.right);
257+
}
258+
}
259+
}
260+
return h;
261+
}
262+
}
263+
264+
class Tuple {
265+
TreeNode node;
266+
int r;
267+
int c;
268+
269+
public Tuple(TreeNode node, int r, int c) {
270+
this.node = node;
271+
this.r = r;
272+
this.c = c;
273+
}
274+
}
275+
```
276+
153277
### **C++**
154278

155279
```cpp
@@ -188,6 +312,55 @@ public:
188312
};
189313
```
190314
315+
```cpp
316+
/**
317+
* Definition for a binary tree node.
318+
* struct TreeNode {
319+
* int val;
320+
* TreeNode *left;
321+
* TreeNode *right;
322+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
323+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
324+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
325+
* };
326+
*/
327+
class Solution {
328+
public:
329+
vector<vector<string>> printTree(TreeNode* root) {
330+
int h = height(root);
331+
int m = h + 1, n = (1 << (h + 1)) - 1;
332+
vector<vector<string>> ans(m, vector<string>(n, ""));
333+
queue<tuple<TreeNode*, int, int>> q;
334+
q.push({root, 0, (n - 1) / 2});
335+
while (!q.empty()) {
336+
auto p = q.front();
337+
q.pop();
338+
root = get<0>(p);
339+
int r = get<1>(p), c = get<2>(p);
340+
ans[r][c] = to_string(root->val);
341+
if (root->left) q.push({root->left, r + 1, c - pow(2, h - r - 1)});
342+
if (root->right) q.push({root->right, r + 1, c + pow(2, h - r - 1)});
343+
}
344+
return ans;
345+
}
346+
347+
int height(TreeNode* root) {
348+
int h = -1;
349+
queue<TreeNode*> q {{root}};
350+
while (!q.empty()) {
351+
++h;
352+
for (int n = q.size(); n; --n) {
353+
root = q.front();
354+
q.pop();
355+
if (root->left) q.push(root->left);
356+
if (root->right) q.push(root->right);
357+
}
358+
}
359+
return h;
360+
}
361+
};
362+
```
363+
191364
### **Go**
192365

193366
```go
@@ -238,6 +411,68 @@ func max(a, b int) int {
238411
}
239412
```
240413

414+
```go
415+
/**
416+
* Definition for a binary tree node.
417+
* type TreeNode struct {
418+
* Val int
419+
* Left *TreeNode
420+
* Right *TreeNode
421+
* }
422+
*/
423+
func printTree(root *TreeNode) [][]string {
424+
h := height(root)
425+
m, n := h+1, (1<<(h+1))-1
426+
ans := make([][]string, m)
427+
for i := range ans {
428+
ans[i] = make([]string, n)
429+
for j := range ans[i] {
430+
ans[i][j] = ""
431+
}
432+
}
433+
q := []tuple{tuple{root, 0, (n - 1) / 2}}
434+
for len(q) > 0 {
435+
p := q[0]
436+
q = q[1:]
437+
root := p.node
438+
r, c := p.r, p.c
439+
ans[r][c] = strconv.Itoa(root.Val)
440+
if root.Left != nil {
441+
q = append(q, tuple{root.Left, r + 1, c - int(math.Pow(float64(2), float64(h-r-1)))})
442+
}
443+
if root.Right != nil {
444+
q = append(q, tuple{root.Right, r + 1, c + int(math.Pow(float64(2), float64(h-r-1)))})
445+
}
446+
}
447+
return ans
448+
}
449+
450+
func height(root *TreeNode) int {
451+
h := -1
452+
q := []*TreeNode{root}
453+
for len(q) > 0 {
454+
h++
455+
for n := len(q); n > 0; n-- {
456+
root := q[0]
457+
q = q[1:]
458+
if root.Left != nil {
459+
q = append(q, root.Left)
460+
}
461+
if root.Right != nil {
462+
q = append(q, root.Right)
463+
}
464+
}
465+
}
466+
return h
467+
}
468+
469+
type tuple struct {
470+
node *TreeNode
471+
r int
472+
c int
473+
}
474+
```
475+
241476
### **TypeScript**
242477

243478
```ts

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /