剑指offer——36二叉树和为某一值的路径

题目描述

输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
 
题解:
  一般涉及到树的题目,首先是想到DFS和BFS了
  
 1 class Solution {
 2 public:
 3     vector<vector<int> > FindPath(TreeNode* root, int expectNumber) {
 4         vector<vector<int>>res;
 5         vector<int>v;
 6         DFS(root, expectNumber, 0, v, res);
 7         sort(res.begin(), res.end(), [](vector<int>a, vector<int>b) {
 8             if (a.size() != b.size())return a.size() > b.size();
 9             for (int i = 0; i < a.size(); ++i)
10                 if (a[i] != b[i])
11                     return a[i] > b[i];
12             return a[0] > b[0];
13         });
14         return res;        
15     }
16     void DFS(TreeNode* root, const int N, int sum, vector<int>&v, vector<vector<int>>&res)
17     {
18         if (root == nullptr)return;
19         v.push_back(root->val);//切记,这样算值的递归,一般是先计算值,然后在递归返回时,再将数据减去
20         sum += root->val;
21         if (sum >= N)
22         {
23             if (sum == N && root->left == nullptr && root->right == nullptr)//判断是不是叶子节点
24                 res.push_back(v);
25             //return;//不知为何这里不要剪枝,剪枝后结果还是错的
26         }
27         DFS(root->left, N, sum, v, res);
28         DFS(root->right, N, sum, v, res);
29         sum -= root->val;
30         v.pop_back();
31     }
32 };

猜你喜欢

转载自www.cnblogs.com/zzw1024/p/11688054.html