leetcode 437. 路徑總和 III
阿新 • • 發佈:2018-04-29
開始 spa 子節點 sum left 返回 leetcode urn nod
給定一個二叉樹,它的每個結點都存放著一個整數值。
找出路徑和等於給定數值的路徑總數。
路徑不需要從根節點開始,也不需要在葉子節點結束,但是路徑方向必須是向下的(只能從父節點到子節點)。
二叉樹不超過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
思路:
- 用兩次dfs(),dfs()用來找從一個結點延伸出的,且路徑等值等於sum的路徑條數,dfs1()用來遍歷每一個結點
- 兩個dfs函數疊加使用就可以求出題中要求
1 class Solution { 2 public: 3 void dfs(TreeNode* root, int sum, int& cnt){ 4 if(root == NULL) return; 5 if(root->val == sum) cnt++; 6 dfs(root->left, sum-root->val, cnt);7 dfs(root->right, sum-root->val, cnt); 8 } 9 10 void dfs1(TreeNode* root, int sum, int& cnt){ 11 if(root == NULL) return; 12 dfs(root, sum, cnt); 13 dfs1(root->left, sum, cnt); 14 dfs1(root->right, sum, cnt); 15 } 16 intpathSum(TreeNode* root, int sum) { 17 int cnt = 0; 18 dfs1(root, sum, cnt); 19 return cnt; 20 } 21 };
leetcode 437. 路徑總和 III