数据结构与算法每日一题——二叉树(102. 二叉树的层序遍历)

47 阅读1分钟

102. 二叉树的层序遍历

/**
 * 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 [];
    const stack = [[root, 0]];
    let ary = [];
    while (stack.length) {
        let [n, l] = stack.shift();
        if (!ary[l]) {
            ary.push([n.val])
        } else {
            ary[l].push(n.val)
        }
        if (n.left) stack.push([n.left, l + 1])
        if (n.right) stack.push([n.right, l + 1])
    }
    return ary
};

// var levelOrder = function(root) {
//   const res = []
//   function traversal (root, depth) {
//     if (root !== null) {
//       if (!res[depth]) {
//         res[depth] = []
//       }
//       traversal(root.left, depth + 1)
//       res[depth].push(root.val)
//       traversal(root.right, depth + 1)
//     }
//   }
//   traversal(root, 0)
//   return res
// }