112. 路径总和
作者:互联网
✅做题思路or感想:
-
也是遍历一遍二叉树的路径,每次遍历一个节点就把
targeSum
减去对应的节点值,如果最后是叶子节点并且targeSum
为0,则符合条件class Solution { public: bool flag = false; void dfs(TreeNode* cur, int sum, int targetSum) { //判断条件 if (sum == targetSum && !cur->left && !cur->right) { flag = true; return; } else { //分别向左右子树遍历 if (cur->left) dfs(cur->left, sum + cur->left->val, targetSum); if (cur->right) dfs(cur->right, sum + cur->right->val, targetSum); } } bool hasPathSum(TreeNode* root, int targetSum) { if (root == nullptr)return false; dfs(root, root->val, targetSum); if (flag)return true; else return false; } };
标签:right,return,cur,sum,路径,dfs,targetSum,112,总和 来源: https://www.cnblogs.com/doomaa/p/16069615.html