LCP 44. 开幕式焰火
题目链接
思路
- 利用广搜并对于扩展出的节点放入哈希表
- 题意可知范围在1——1000,枚举这个范围,如果此值在哈希表中有记录,计数sum+1
题解
function numColor(root: TreeNode | null): number {
let hash = {}
function transfer(root) {
if (root) {
hash[root.val] = 1
transfer(root.left)
transfer(root.right)
}
}
let i: number, sum = 0
transfer(root)
for (i = 1; i <= 1000; i++) {
if (hash[i]) ++sum
}
return sum
};
102. 二叉树的层序遍历
题目链接
思路
- 先将根节点塞入数组中
- 根据深度来选择放入结果数组的哪一层
题解
function levelOrder(root: TreeNode | null): number[][] {
const ret = [];
if (!root) {
return ret;
}
const q = [];
q.push(root);
while (q.length !== 0) {
const currentLevelSize = q.length;
ret.push([]);
for (let i = 1; i <= currentLevelSize; ++i) {
const node = q.shift();
ret[ret.length - 1].push(node.val);
if (node.left) q.push(node.left);
if (node.right) q.push(node.right);
}
}
return ret;
};
1609. 奇偶树
题目链接
思路
在上面一道题得到结果后,先判断结果数组是否满足奇数索引里面的值都为偶数,偶数索引值都为奇数,且:
- 偶数下标 层上的所有节点的值都是 奇 整数,从左到右按顺序 严格递增
- 奇数下标 层上的所有节点的值都是 偶 整数,从左到右按顺序 严格递减
题解
function isEvenOddTree(root: TreeNode | null): boolean {
const ret = [];
if (!root) {
return false;
}
const q = [];
q.push(root);
while (q.length !== 0) {
const currentLevelSize = q.length;
ret.push([]);
for (let i = 1; i <= currentLevelSize; ++i) {
const node = q.shift();
ret[ret.length - 1].push(node.val);
if (node.left) q.push(node.left);
if (node.right) q.push(node.right);
}
}
for (let i = 0; i < ret.length; i++) {
if (i & 1) {
//偶数,严格递减
for (let j = 0; j < ret[i].length; ++j) {
if ((ret[i][j] & 1) || (j && ret[i][j] >= ret[i][j - 1])) {
return false
}
}
} else {
// 奇数,单调递增
for (let j = 0; j < ret[i].length; ++j) {
if (!(ret[i][j] & 1) || (j && ret[i][j] <= ret[i][j - 1])) {
return false
}
}
}
}
return true;
};