We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
Given the below binary tree and sum = 22,
sum = 22
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
5->4->11->2
22
The text was updated successfully, but these errors were encountered:
/** * 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; } };
Sorry, something went wrong.
No branches or pull requests
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
.The text was updated successfully, but these errors were encountered: