Leetcode-437. 路径总和 III(Java)
給定一個二叉樹,它的每個結點都存放著一個整數值。
找出路徑和等于給定數值的路徑總數。
路徑不需要從根節點開始,也不需要在葉子節點結束,但是路徑方向必須是向下的(只能從父節點到子節點)。
二叉樹不超過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 的路徑有:
1. ?5 -> 3
2. ?5 -> 2 -> 1
3. ?-3 -> 11
思路:先序遍歷將所有結點都作為根結點
再先序遍歷得出每個結點作為根節點時,路徑和為目標值的結果
代碼:
/**
?*?Definition?for?a?binary?tree?node.
?*?public?class?TreeNode?{
?*?????int?val;
?*?????TreeNode?left;
?*?????TreeNode?right;
?*?????TreeNode(int?x)?{?val?=?x;?}
?*?}
?*/
class?Solution?{
????int?count=0;
????public?int?pathSum(TreeNode?root,?int?sum)?{
????????if(root==null)?return?0;
????????helper(root,sum);
????????pathSum(root.left,sum);
????????pathSum(root.right,sum);
????????return?count;
????}
????public?void?helper(TreeNode?root,?int?sum){
????????if(root?==?null)?return;
????????sum-=root.val;
????????if(sum?==?0){
????????????count++;???????????
????????}
????????helper(root.left,sum);
????????helper(root.right,sum);
????}?
}
總結
以上是生活随笔為你收集整理的Leetcode-437. 路径总和 III(Java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode--152. 乘积最大子
- 下一篇: Leetcode--55. 跳跃游戏