This is the 19th day of my participation in the August Wenwen Challenge.More challenges in August


Note: Part of the article content and pictures from the network, if there is infringement please contact me (homepage public number: small siege lion learning front)

By: Little front-end siege lion, home page: little front-end siege lion home page, source: Nuggets

GitHub: P-J27, CSDN: PJ wants to be a front-end siege lion

Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.


LeetCode 102. Hierarchical traversal of binary trees – JavaScript

Topic describes

Given a binary tree, return the value of the nodes traversed hierarchically. (That is, layer by layer, all nodes are accessed from left to right).

For example given a binary tree:

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

Returns the result of its hierarchical traversal:

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

As can be seen from the question, this question examines the order traversal of the binary tree, and reflects the “hierarchy” in the result.


Train of thought

By slightly changing the use of queues, you can show the hierarchy in the traversal process as follows:

  • Initialize queue to store the nodes of the current layer
  • checkWhether queue is empty
    • If not empty: traverses all nodes in the current queue,Check the left and right children of each node, place the non-empty child nodes in the queue and continue the loop
    • If empty: breaks the loop

On the above idea, a little transformation is ok. The code is as follows:

var levelOrder = function(root) {
  if(! root)return [];
  const queue = [root];
  const res = []; // Store the traversal result
  let level = 0; // Indicates the current level
  while (queue.length) {
    res[level] = []; // Level traversal result

    let levelNum = queue.length; // Number of nodes at level 1
    while (levelNum--) {
      const front = queue.shift();
      res[level].push(front.val);
      if (front.left) queue.push(front.left);
      if (front.right) queue.push(front.right);
    }

    level++;
  }
  return res;
};
Copy the code

Thank you for reading, I hope to help you, if there is a mistake or infringement of the article, you can leave a message in the comment area or add a public number in my home page to contact me.

Writing is not easy, if you feel good, you can “like” + “comment” thanks for your support ❤