jan-brennenstuhl-HwtWJ5LraB8-unsplash.jpg

官方题解(这题我不会)

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val, left, right) {
  4. * this.val = (val===undefined ? 0 : val)
  5. * this.left = (left===undefined ? null : left)
  6. * this.right = (right===undefined ? null : right)
  7. * }
  8. */
  9. /**
  10. * @param {TreeNode} root
  11. * @return {number[][]}
  12. */
  13. var levelOrder = function (root) {
  14. const ret = [];
  15. if (!root) {
  16. return ret;
  17. }
  18. const q = [];
  19. q.push(root);
  20. while (q.length !== 0) {
  21. const currentLevelSize = q.length;
  22. ret.push([]);
  23. for (let i = 1; i <= currentLevelSize; ++i) {
  24. const node = q.shift();
  25. ret[ret.length - 1].push(node.val);
  26. if (node.left) q.push(node.left);
  27. if (node.right) q.push(node.right);
  28. }
  29. }
  30. return ret;
  31. };

解题思路(队列queue,广度优先搜索DFS)

使用队列先入先出的特性,依次填入根节点、左子树、右子树,之后再依次抛出即可。``