124. 二叉树中的最大路径和
leetcode-cn.com/problems/bi…
- dfs 后续遍历
如果使用全局记录最大值,只需要在递归的时候 return 当前的一条边(上面提了不能拐),并在函数内部计算以当前节点出发的最大路径和,并更新全局最大值即可。 这里的核心其实是 return 较大的一条边
var maxPathSum = function (root) {
// let res = Math.max(res,Math.max(left,0)+Math.max(right,0)+root.val)
let res = Number.MIN_SAFE_INTEGER
const dfs = (root) => {
if (!root) {
return 0
}
const left = dfs(root.left)
const right = dfs(root.right)
res = Math.max(res, Math.max(left, 0) + Math.max(right, 0) + root.val)
return Math.max(left,right,0) + root.val
}
dfs(root)
return res
};
面试题 04.12. 求和路径
leetcode-cn.com/problems/pa…
var pathSum = function (root, sum) {
let counter = 0
const preOrder = (root) => {
if (!root) {
return
}
dfs(root, sum)
preOrder(root.left)
preOrder(root.right)
}
const dfs = (root, sum) => {
if (!root) {
return
}
if (sum === root.val) {
counter++
}
dfs(root.left, sum - root.val)
dfs(root.right, sum - root.val)
}
preOrder(root)
return counter
};
563. 二叉树的坡度
leetcode-cn.com/problems/bi…
var findTilt = function(root) {
let sum = 0
const dfs = (root)=>{
if(!root){
return 0
}
const left = dfs(root.left)
const right = dfs(root.right)
sum = sum + Math.abs(left-right)
return left + right + root.val
}
dfs(root)
return sum
};
129. 求根到叶子节点数字之和
leetcode-cn.com/problems/su…
var sumNumbers = function(root) {
let sum = 0
const dfs = (root,res)=>{
if(!root){
return
}
res = res * 10 + root.val
if(!root.left && !root.right){
sum = sum + res
return
}
dfs(root.left,res)
dfs(root.right,res)
}
dfs(root,0)
return sum
};