Problem:
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Summary:
找到二叉树中的子路径条数使得该子路径权值之和与给定和相等。
Analysis:
本题参考:http://www.cnblogs.com/grandyang/p/6007336.html
1. 最直观的思路:通过前序遍历的方式遍历二叉树,每遍历至一个节点,将当前节点的权值记录在数组中,并更新记录当前路径和的变量curSum,同时判断更新后的curSum与 sum是否相等,若相等则res加1。
此时的curSum为从根节点到当前节点的路径之和。至于这条路径上的子路径是否满足题意,则需将数组中的权值在curSum中一个个减掉,每剪掉一个,判断一次当前权值和是否与sum相等,若相等则res加1。此处需注意不能将数组中的权值完全减掉,最后应保留一个,因为全部去掉所得curSum为0,若题中所给的sum刚好为0,则判断相等,但不符合题意。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int pathSum(TreeNode* root, int sum) { 13 int res = 0; 14 vector<TreeNode*> vec; 15 findPath(root, sum, 0, res, vec); 16 17 return res; 18 } 19 20 void findPath(TreeNode* node, int sum, int curSum, int &res, vector<TreeNode*> &vec) { 21 if (!node) return; 22 curSum += node->val; 23 vec.push_back(node); 24 25 if (sum == curSum) res++; 26 int tmp = curSum; 27 for (int i = 0; i < vec.size() - 1; i++) { 28 tmp -= vec[i]->val; 29 if (tmp == sum) res++; 30 } 31 32 findPath(node->left, sum, curSum, res, vec); 33 findPath(node->right, sum, curSum, res, vec); 34 35 vec.pop_back(); 36 } 37 };
2. 优化算法,用hash表记录当前遍历路径中的子路径权值和对应出现的次数。
- 若sum为从根节点到某x节点的路径权值和,则遍历至节点x时,当前的路径和curSum恰好与sum相等,则res = m[curSum - sum] = m[0] = 1;
- 若sum为某段子路径权值和,如:x1->x2->x3->x4......中sum等于节点x3与节点x4的权值和,即sum = sumx3+x4。则遍历至x2时, m[curSum]++; 处已经记录了m[curSum] = m[sumx1+x2] = 1,便利至x4时curSum = sumx1+x2+x3+x4,则res = m[curSum - sum] = m[sumx1+x2+x3+x4 - sumx3+x4] = m[sumx1+x2] = 1。
1 class Solution { 2 public: 3 int pathSum(TreeNode* root, int sum) { 4 unordered_map<int, int> m; 5 m[0] = 1; 6 int res = findPath(root, sum, 0, m); 7 8 return res; 9 } 10 11 int findPath(TreeNode* node, int sum, int curSum, unordered_map<int, int> &m) { 12 if (!node) return 0; 13 curSum += node->val; 14 15 int res = m[curSum - sum]; 16 m[curSum]++; 17 res += (findPath(node->left, sum, curSum, m) + findPath(node->right, sum, curSum, m)); 18 m[curSum]--; 19 20 return res; 21 } 22 };
3. 最简洁的方法,以每一个节点作为路径根节点进行前序遍历,查找每一条路径的权值和与sum是否相等。
1 class Solution { 2 public: 3 int pathSum(TreeNode* root, int sum) { 4 if (!root) return 0; 5 int res = findPath(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum); 6 return res; 7 } 8 9 int findPath(TreeNode* node, int curSum, int sum) { 10 if (!node) return 0; 11 curSum += node->val; 12 return (curSum == sum) + findPath(node->left, curSum, sum) + findPath(node->right, curSum, sum); 13 } 14 };