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
解题思想: 在深度优先遍历的过程中,记录当前路径的节点值的和。 在叶子节点处,判断当前路径的节点值的和是否等于目标值。
代码:
var hasPathSum = function(root, sum) { if(!root) return false; let res = false; const dfs = (node, s) => { // console.log(node.val, s); // 如果是叶子节点,且当前路径的和为sum,就证明找到一个符合要求的路径 if (!node.left && !node.right && s === sum) { res = true; } if(node.left) dfs(node.left, s + node.left.val); if(node.right) dfs(node.right, s + node.right.val); }; dfs(root, root.val); return res; };
复杂度分析:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
方法一:深度优先遍历
解题思想:
在深度优先遍历的过程中,记录当前路径的节点值的和。
在叶子节点处,判断当前路径的节点值的和是否等于目标值。
代码:
复杂度分析:
The text was updated successfully, but these errors were encountered: