题目描述

原题链接

个人解法

Javascript

BFS

  1. /*
  2. * @lc app=leetcode.cn id=102 lang=javascript
  3. *
  4. * [102] 二叉树的层序遍历
  5. */
  6. // @lc code=start
  7. /**
  8. * Definition for a binary tree node.
  9. * function TreeNode(val, left, right) {
  10. * this.val = (val===undefined ? 0 : val)
  11. * this.left = (left===undefined ? null : left)
  12. * this.right = (right===undefined ? null : right)
  13. * }
  14. */
  15. /**
  16. * @param {TreeNode} root
  17. * @return {number[][]}
  18. */
  19. var levelOrder = function (root) {
  20. const result = [];
  21. if (root === null) {
  22. return [];
  23. }
  24. const myLevelOrder = function (roots) {
  25. const len = roots.length;
  26. if (len === 0) {
  27. return;
  28. } else {
  29. let temp = [];
  30. let nextRoots = [];
  31. for (let i = 0; i < len; i++) {
  32. temp.push(roots[i].val);
  33. roots[i].left && nextRoots.push(roots[i].left);
  34. roots[i].right && nextRoots.push(roots[i].right);
  35. }
  36. result.push(temp);
  37. myLevelOrder(nextRoots);
  38. }
  39. }
  40. myLevelOrder([root]);
  41. return result;
  42. };
  43. // @lc code=end

Java

其他解法

Java

Javascript

官方 BFS

题解链接

  1. var levelOrder = function(root) {
  2. const ret = [];
  3. if (!root) {
  4. return ret;
  5. }
  6. const q = [];
  7. q.push(root);
  8. while (q.length !== 0) {
  9. const currentLevelSize = q.length;
  10. ret.push([]);
  11. for (let i = 1; i <= currentLevelSize; ++i) {
  12. const node = q.shift();
  13. ret[ret.length - 1].push(node.val);
  14. if (node.left) q.push(node.left);
  15. if (node.right) q.push(node.right);
  16. }
  17. }
  18. return ret;
  19. };