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

Contents
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.
|
|
最後祝福努力認真的各位 “All your dream of are hidden in your daily life” 我們峰頂見!!!