DEV Community

Akhil
Akhil

Posted on

3 1

Binary Tree Level Order Traversal

Question: give a tree, return the level order traversal of the tree.

so for given tree:

Alt Text

output would be :

[ [10],
  [5 ,7 ],
  [15, 9, 20]
]
Enter fullscreen mode Exit fullscreen mode

So what is meant by level order traversal?

Alt Text

If you observe closely, it's a Breadth-first traversal algorithm.

So question boils down to how to Breadth-first traverse a tree.

Read more about it : https://www.hackerearth.com/practice/algorithms/graphs/breadth-first-search/tutorial/

So for this question solution is :

var levelOrder = function(root) {
  if (!root) return [];

  const res = [];
  const q = [];
  q.push(root);

  while(q.length) {
    const lvl = [];
    const size = q.length;

    for (let i = 0; i < size; i++) {
      const node = q.shift();
      lvl.push(node.val);
      if (node.left) q.push(node.left);
      if (node.right) q.push(node.right);
    }
    res.push(lvl);
  }
  return res;
};
Enter fullscreen mode Exit fullscreen mode

github:https://github.com/AKHILP96/Data-Structures-and-Algorithms/blob/master/Algorithm/breadthFirstSearch.js

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay