Open Zheaoli opened 1 year ago
/*
* @lc app=leetcode id=102 lang=typescript
*
* [102] Binary Tree Level Order Traversal
*/
// @lc code=start
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function levelOrder(root: TreeNode | null): number[][] {
const ans = [] as number[][];
const queue = [] as TreeNode[];
queue.push(root);
while (queue.length) {
const levelVal = [] as number[];
const len = queue.length;
for (let i = 0; i < len; i++) {
const node = queue.shift();
if (node) {
levelVal.push(node.val);
node.left && queue.push(node.left);
node.right && queue.push(node.right);
}
}
// make sure level is not empty
levelVal.length && ans.push(levelVal);
}
return ans;
};
// @lc code=end
微信id: 弘树 来自 vscode 插件
2022-10-10