二叉树层序遍历
给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
例如:
给定的二叉树是{3,9,20,#,#,15,7},结果是[[3],[9,20],[15,7]]
/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
/**
*
* @param root TreeNode类
* @return int整型二维数组
*/
function levelOrder( root ) {
if (!root) return [];
const stack = [root];
const result = [];
const temp = [];
let len = 0;
while(len = stack.length) {
for(let i = 0; i < len; i++) {
const node = stack.shift();
temp.push(node.val);
if (node.left) stack.push(node.left);
if (node.right) stack.push(node.right);
}
result.push([...temp]);
temp.length = 0;
}
return result;
}
module.exports = {
levelOrder : levelOrder
};树算法 文章被收录于专栏
树相关算法


腾讯公司福利 1143人发布