题解 | #求二叉树的层序遍历#

求二叉树的层序遍历

http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */

/**
  * 
  * @param root TreeNode类 
  * @return int整型二维数组
  */
function levelOrder( root ) {
    let arr = [];
    if (root != null) {
        dfs(root, 0, arr);
    }
    return arr;
}


function dfs(treeNode, step, arr) {
    arr[step] = arr[step] ? arr[step] : arr.splice(step, 0, []);
    arr[step].push(treeNode.val);
    if (treeNode.left != null) {
        dfs(treeNode.left, step + 1, arr);
    }
    if (treeNode.right != null) {
        dfs(treeNode.right, step + 1, arr);
    }
}

module.exports = {
    levelOrder : levelOrder
};
全部评论

相关推荐

头像
不愿透露姓名的神秘牛友
04-08 00:50
点赞 评论 收藏
转发
投递腾讯云智研发等公司6个岗位
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务