美文网首页
2020-07-25 102. Binary Tree Leve

2020-07-25 102. Binary Tree Leve

作者: 苦庭 | 来源:发表于2020-07-25 06:18 被阅读0次

    https://leetcode.com/problems/binary-tree-level-order-traversal

    /**

    • Definition for a binary tree node.
    • function TreeNode(val, left, right) {
    • this.val = (val===undefined ? 0 : val)
      
    • this.left = (left===undefined ? null : left)
      
    • this.right = (right===undefined ? null : right)
      
    • }
      /
      /
      *
    • @param {TreeNode} root
    • @return {number[][]}
      */
      var levelOrder = function(root) {
      if(!root) return [];
      let res = [];
      let queue = [root];
      while(queue.length>0) {
      let stack = [];
      for(let i=queue.length; i>0; i--){
      let cur = queue.shift();
      stack.push(cur.val);
      if(cur.left) {
      queue.push(cur.left);
      }
      if(cur.right) {
      queue.push(cur.right);
      }
      }
      res.push(stack);
      }
      return res;
      };

    相关文章

      网友评论

          本文标题:2020-07-25 102. Binary Tree Leve

          本文链接:https://www.haomeiwen.com/subject/fszulktx.html