题目:二叉树中和为某一值的路径
题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
思路
递归到尽头,判断是否符合条件
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<vector<int> > res;
vector<int> row;
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if(root==NULL) return res;
row.push_back(root->val);
expectNumber = expectNumber - root->val;
if(expectNumber==0 && root->left==NULL && root->right==NULL)
res.push_back(row);
else{
FindPath(root->left, expectNumber);
FindPath(root->right, expectNumber);
}
row.pop_back();
return res;
}
};
因为题目说要排序,补上排序的代码。不过上面居然过了全部的测试用例。
#include<bits/stdc++.h>
using namespace std;
bool cmp(const vector<int> &a, const vector<int> &b){
return a.size()>b.size();
}
int main(){
vector<vector<int> >v = {
{1,2,3,4},
{1,2,3,4,5,6},
{1},
{1,2,3,6}
};
sort(v.begin(), v.end(), cmp);
for(int i=0;i<v.size();i++){
for(int j=0;j<v[i].size();j++){
cout<<" "<<v[i][j];
}
cout<<endl;
}
return 0;
}