01.二叉树的层序遍历
思路:使用队列实现一层一层遍历的要求,对每一层进行遍历,将其val存到临时数组中,并将节点的左右节点存到队列中,用于进行下一层遍历
function levelOrder(root: TreeNode | null): number[][] {
const queue:TreeNode[] = []
const ans:number[][] = []
let tmpArr:number[] = []
if (root != null) queue.push(root)
let cur:TreeNode = null
while (queue.length > 0) {
// 循环的次数要使用一个定值,即这次while循环开始时,队列的长度
for (let i = 0, len = queue.length; i < len; i++) {
cur = queue.shift()
tmpArr.push(cur.val)
if (cur.left != null) queue.push(cur.left)
if (cur.right != null) queue.push(cur.right)
}
ans.push(tmpArr)
tmpArr = []
}
return ans
};
02.二叉树的层序遍历II
思路:自底向上遍历二叉树,就是自上而下遍历,然后将数组反转即可
function levelOrderBottom(root: TreeNode | null): number[][] {
let helperQueue: TreeNode[] = [];
let resArr: number[][] = [];
let tempArr: number[] = [];
let tempNode: TreeNode;
if (root !== null) helperQueue.push(root);
while (helperQueue.length > 0) {
for (let i = 0, length = helperQueue.length; i < length; i++) {
tempNode = helperQueue.shift()!;
tempArr.push(tempNode.val);
if (tempNode.left !== null) helperQueue.push(tempNode.left);
if (tempNode.right !== null) helperQueue.push(tempNode.right);
}
resArr.push(tempArr);
tempArr = [];
}
return resArr.reverse();
};