The title

The binary tree is printed from top to bottom layer, with nodes of the same layer printed from left to right, each layer printed to a row.

For example, given a binary tree: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
Copy the code

Returns the result of its hierarchical traversal:

[[3], [9,20], [15,7]Copy the code

 

Source: LeetCode leetcode-cn.com/problems/co…

Their thinking

  1. So they want to print the binary tree from top to bottom, layer by layer
  2. Then we can use an array to hold the values of the nodes and the depth of the nodes
  3. When traversing a node, add the node value to the corresponding depth (i.e. the layer corresponding to the depth) using node depth as array subscript

Code implementation

var levelOrder = function(root) { const queue = [{node:root, dep: 0}] const ans = [] while(queue.length) { const item = queue.shift() if (! item.node) continue; if (! ans[item.dep]) ans[item.dep] = []; ans[item.dep].push(item.node.val) queue.push({node: item.node.left, dep: item.dep + 1}) queue.push({node: item.node.right, dep: item.dep + 1}) } return ans };Copy the code

If there are mistakes welcome to point out, welcome to discuss together!