@@ -272,60 +272,56 @@ func main() {
272
272
273
273
> 按层打印输出二叉树
274
274
275
- ``` Java
276
- package class07 ;
277
-
278
- import java.util.LinkedList ;
279
- import java.util.Queue ;
275
+ ``` GO
276
+ package main
280
277
281
- public class Code03_LevelTraversalBT {
278
+ import " fmt "
282
279
283
- public static class Node {
284
- public int value;
285
- public Node left;
286
- public Node right;
280
+ type Node struct {
281
+ // 二叉树节点上的值
282
+ Val int
283
+ // 左孩子
284
+ Left *Node
285
+ // 右孩子
286
+ Right *Node
287
+ }
287
288
288
- public Node (int v ) {
289
- value = v;
290
- }
289
+ // Level 按层遍历二叉树
290
+ func (head *Node ) Level () {
291
+ if head == nil {
292
+ return
291
293
}
292
-
293
- public static void level (Node head ) {
294
- if (head == null ) {
295
- return ;
294
+ hd := head
295
+ // 简单实现一个队列
296
+ queue := make ([]*Node, 0 )
297
+ // 加入头结点
298
+ queue = append (queue, hd)
299
+ // 队列不为空出队打印,把当前节点的左右孩子加入队列
300
+ for len (queue) != 0 {
301
+ // 弹出队列头部的元素
302
+ cur := queue[0 ]
303
+ queue = queue[1 :]
304
+ fmt.Println (cur.Val )
305
+ if cur.Left != nil {
306
+ queue = append (queue, cur.Left )
296
307
}
297
- // 准备一个辅助队列
298
- Queue<Node > queue = new LinkedList<> ();
299
- // 加入头结点
300
- queue. add(head);
301
- // 队列不为空出队打印,把当前节点的左右孩子加入队列
302
- while (! queue. isEmpty()) {
303
- Node cur = queue. poll();
304
- System . out. println(cur. value);
305
- if (cur. left != null ) {
306
- queue. add(cur. left);
307
- }
308
- if (cur. right != null ) {
309
- queue. add(cur. right);
310
- }
308
+ if cur.Right != nil {
309
+ queue = append (queue, cur.Right )
311
310
}
312
311
}
312
+ }
313
313
314
- public static void main (String [] args ) {
315
- Node head = new Node (1 );
316
- head. left = new Node (2 );
317
- head. right = new Node (3 );
318
- head. left. left = new Node (4 );
319
- head. left. right = new Node (5 );
320
- head. right. left = new Node (6 );
321
- head. right. right = new Node (7 );
322
-
323
- level(head);
324
- System . out. println(" ========" );
325
- }
314
+ func main () {
315
+ head := &Node{Val: 1 }
316
+ head.Left = &Node{Val: 2 }
317
+ head.Right = &Node{Val: 3 }
318
+ head.Left .Left = &Node{Val: 4 }
319
+ head.Left .Right = &Node{Val: 5 }
320
+ head.Right .Left = &Node{Val: 6 }
321
+ head.Right .Right = &Node{Val: 7 }
326
322
323
+ head.Level ()
327
324
}
328
-
329
325
```
330
326
331
327
> 找到二叉树的最大宽度
0 commit comments