首先我的想法是递归,从root节点开始,一直遍历到各个leaf节点,计算各条路径的sum。 开始的递归代码如下: 1intaddToSum(TreeNode* root,intresult){2if(root==NULL)return0;3addToSum(root->left,result);4result+=root->val;5} 这段递归有点问题:首先只是计算root的左节点路径的Sum,如上图:是5->4->11-...
bool hasPathSum(TreeNode *root, int sum) { return hasPathSum(root,sum,0); } private: bool hasPathSum(TreeNode *root, int sum, int CurrSum){ if(!root)return false; CurrSum+=root->val; if((!root->left)&&(!root->right))return CurrSum==sum; return hasPathSum(root->left,sum,C...
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree andsum = 22, return true, as there exist a root-to-leaf path5->4->11->2which sum is...
if mysum == target_sum: return True else: return False else: mysum += root.val a = self.dfs(root.left, mysum, target_sum) b = self.dfs(root.right, mysum, target_sum) return a or b def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: boo...
left, sum, curSum, map) + preOrder(root.right, sum, curSum, map); map.put(curSum, map.get(curSum) - 1); return res; } 当然这道题目也可以使用递归的方法做,只不过时间复杂度较高。具体代码如下: public int pathSum(TreeNode root, int sum) { if (root == null) return 0; return...
/* * @lc app=leetcode id=437 lang=javascript * * [437] Path Sum III *//** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */function helper(root, acc, target, hashmap) { // see also :...
left, remainSum): return True # 当右子结点存在,且存在一条右子结点到叶子路径上所有值到和为 remainSum ,则满足题意 if root.right and self.hasPathSum(root.right, remainSum): return True # 左右子结点都不满足题意,返回 false return False 代码(Go) /** * Definition for a binary tree node...
if(root->left)helper(root->left,value,v); if(root->right)helper(root->right,value,v); v.pop_back(); } vector<vector<int>> pathSum(TreeNode* root,intsum) { vector<int> v; helper(root,sum,v); returnres; } }; 想法: 还需要pop_back(), 理解!
classSolution{privateMap<Long,Integer> map;privateintresult=, target =;publicintpathSum(TreeNode root,int targetSum){if(root ==null)return; target = targetSum; map =newHashMap(); map.put(0L,1); dfs(root, root.val);return result;}publicvoiddfs(TreeNode node,long value){ ...
return true, as there exist a root-to-leaf path5->4->11->2which sum is 22. 检查一颗二叉树是否有和某数相等的路径。和前面的最少深度二叉树思路差不多。 1 每进入一层,如果该层跟节点不为空,那么就加上这个值。 2 如果到了叶子节点,那么就与这个特定数比较,相等就说明存在这样的路径。