Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
Topic describes
Each node of the binary tree is printed from top to bottom, and nodes of the same level are printed from left to right.
For example, given a binary tree: [3,9,20,null,null,15,7],
return
- Tip:
'Total number of nodes <= 1000'Copy the code
Implementation approach
Because it’s a binary tree, traversing a binary tree requires depth first and breadth first.
1->2->4->5->3->6->7)
(1->2->3->4->5->6->7)
Breadth-first solution: We use queue first-in, first-out principle is used to determine the order of execution, the home page to create a queue queue to head node into the queue and out into a while loop, added to the print queue queue dequeue element array around nodes exist in left node priority order into the queue, so know print queue queue is empty after the output array.
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; *} * /
/ * * *@param {TreeNode} root
* @return {number[]}* /
var levelOrder = function(root) {
let list = []
if(! root)return []
const queue = [root] // The head node is queued
while (queue.length > 0) {
let item = queue.shift()
list.push(item.val) // Prints the array
item.left && queue.push(item.left) // The left node is queued
item.right && queue.push(item.right) // The right node is queued
}
return list
};
Copy the code