Contents

[Golang][Leetcode][BinaryTree]刷題系列-102-Level Order Traversal


102. Binary Tree Level Order Traversal


Level : Medium

原題連結 : Click

題目 :

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).


Example :

Note

Example 1:

Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]]

Example 2:

Input: root = [1] Output: [[1]]

Example 3:

Input: root = [] Output: []


解題思路 :

  • 這題其實就是用到queue的資料結構,並帶入廣度優先搜尋(BFS)的概念也就是廣義的level order traversal
  • Graph常用到的bfs就是從tree的level order traversal推廣過去的
  • 在binary tree這邊觀念很簡單就是一level為單位去遍歷
  • 在搭配queue資料結構,當node從queue左邊出來時就把他的left childNode & right childNode從右邊放進去
  • 並掌握每一round queue的長度,決定好每一round要拿出node的數量

Queue解法

  • time complexity: O(n) , space complexity: O(n)

Runtime: 0 ms, faster than 100.00% of Go online submissions for Binary Tree Level Order Traversal.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func levelOrder(root *TreeNode) [][]int {
    

    
    var queue []*TreeNode
    
    var res [][]int
    
    if root == nil {
        return res
    } 
    
    queue = append(queue, root)
    
    for len(queue) != 0 {
        
        length := len(queue)
        
        tempArr := make([]int,0)
        
        for i := 0; i < length; i++ {
            node := queue[0]
            
            queue = queue[1:]
            
            if node.Left != nil {
                queue = append(queue, node.Left)
            }
            
            if node.Right != nil {
                queue = append(queue, node.Right)
            }
            
            tempArr = append(tempArr, node.Val)
        }
        
        res = append(res, tempArr)
        
    }
    return res
    
}

最後祝福努力認真的各位 “All your dream of are hidden in your daily life” 我們峰頂見!!!