問題描述:
給定一個二叉樹,找出所有路徑中各節點相加總和等於給定 目標值
的路徑。
一個有效的路徑,指的是從根節點到葉節點的路徑。
解題思路:對每條路徑進行加和,與給定的值比較,若相等,加到向量中。
代碼:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of binary tree
* @param target an integer
* @return all valid paths
*/
vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
vector<vector<int> >paths;
vector<int>path;
vector<int>::iterator it;
if(root==NULL){
return paths;
}
else {
def(root,paths,path,target);
return paths;
}
}
void def(TreeNode*root,vector<vector<int> >&ps,vector<int>p,int target){
p.push_back(root->val);
vector<int>::iterator itp;
if(root->left==NULL&&root->right==NULL){
int flag=0;
for(itp=p.begin();itp!=p.end();itp++){
flag+=*itp;
}
if(flag==target){
ps.push_back(p);
}
}
if(root->left!=NULL){
def(root->left,ps,p,target);
}
if(root->right!=NULL){
def(root->right,ps,p,target);
}
// Write your code here
}
};
感想:
注意思路