本文主要是介绍Leetcode 437. 路径总和 III,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述
给定一个二叉树,它的每个结点都存放着一个整数值。
找出路径和等于给定数值的路径总数。
路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
示例:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10/ \
5 -3
/ \
3 2 11
/ \
3 -2 1
返回 3。和等于 8 的路径有:
- 5 -> 3
- 5 -> 2 -> 1
- -3 -> 11
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
C++
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
/*双重递归*/
class Solution {public:int res=0;int pathSum(TreeNode* root, int sum) {if(!root) return 0;preorder(root,sum);pathSum(root->left,sum);pathSum(root->right,sum);return res;}void preorder(TreeNode* root,int sum){if(!root) return;if(root->val==sum) res++;preorder(root->left,sum-root->val);preorder(root->right,sum-root->val);}
};
这篇关于Leetcode 437. 路径总和 III的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!