Open Tcdian opened 4 years ago
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} sum
* @return {boolean}
*/
var hasPathSum = function(root, sum) {
let accumVal = 0;
let result = false;
dfs(root);
return result;
function dfs(root) {
if (root === null || result) {
return;
}
accumVal += root.val;
if (accumVal === sum && root.left === null && root.right === null) {
result = true;
return;
}
dfs(root.left);
dfs(root.right);
accumVal -= root.val;
}
};
/**
* 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 hasPathSum(root: TreeNode | null, sum: number): boolean {
let accumVal = 0;
let result = false;
dfs(root);
return result;
function dfs(root: TreeNode | null) {
if (root === null || result) {
return;
}
accumVal += root.val;
if (accumVal === sum && root.left === null && root.right === null) {
result = true;
return;
}
dfs(root.left);
dfs(root.right);
accumVal -= root.val;
}
};
112. Path Sum
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
Note
Example
Given the below binary tree and
sum = 22
,return true, as there exist a root-to-leaf path
5->4->11->2
which sum is22
.