题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
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
};