二叉树:二叉树中和为某一值的路径

66 阅读1分钟

image.png

方法

  1. 递归遍历,每一次遍历都计算出,要达到sum还差多少,直到计算出总和。
function hasPathSum( root ,  sum ) {
    if(!root) return false
    
    return dfs(root, sum);
}

function dfs(root, target) {
    if(!root) return false
    target -= root.val; // 计算出目标值
    
    // 是叶子结点,并且target为0
    if(!root.left && !root.right && target==0) {
        return true;
    }
    return dfs(root.left, target) || dfs(root.right, target);

}