662. 二叉树最大宽度
leetcode-cn.com/problems/ma…
var widthOfBinaryTree = function (root) {
const stack = [{
node: root,
pos: 1n
}]
let maxCounter = 0n
while (stack.length) {
const size = stack.length
let posLeft = stack[0].pos
let posRight = stack[stack.length -1].pos
if(maxCounter - (posRight - posLeft + 1n) < 0n){
maxCounter = posRight - posLeft + 1n
}
for (let i = 0
const { node, pos } = stack.shift()
if (node.left) {
stack.push({
node: node.left,
pos: 2n * pos
})
}
if(node.right){
stack.push({
node: node.right,
pos: 2n * pos + 1n
})
}
}
}
return maxCounter
}
1372. 二叉树中的最长交错路径
leetcode-cn.com/problems/lo…
var longestZigZag = function (root) {
const Left = -1
const Right = 1
let maxCounter = 0
const dfs = (node, dir, counter) => {
if (node === null) {
return
}
maxCounter = Math.max(maxCounter, counter)
if (dir === Left) {
dfs(node.left, Left, 1)
dfs(node.right, Right, counter + 1)
}
if (dir === Right) {
dfs(node.left, Left, counter + 1)
dfs(node.right, Right, 1)
}
}
dfs(root.left, Left, 1)
dfs(root.right, Right, 1)
return maxCounter
};
113. 路径总和 II
leetcode-cn.com/problems/pa…
var pathSum = function(root, targetSum) {
const paths = []
const dfs = (node,path,pathSum)=>{
if(node ===null){
return
}
if(!node.left && !node.right){
if(pathSum === node.val){
paths.push([...path,node.val].slice())
}
return
}
path.push(node.val)
dfs(node.left,path,pathSum - node.val)
dfs(node.right,path,pathSum - node.val)
path.pop()
}
dfs(root,[],targetSum)
return paths
};