二叉树的路径和---递归返回时要弹出向量尾的元素,不管是否找到。

来源:互联网 发布:2017大学生贷款软件 编辑:程序博客网 时间:2024/06/04 18:14

给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值的路径。

一个有效的路径,指的是从根节点到叶节点的路径。

http://www.lintcode.com/zh-cn/problem/binary-tree-path-sum/

样例

给定一个二叉树,和 目标值 = 5:

     1    / \   2   4  / \ 2   3

返回:

[  [1, 2, 2],  [1, 4]]
#include <iostream>#include <vector>#include <string>#include <sstream> #include <stack> #include <iostream>#include <algorithm>#include <math.h>#include <limits.h>using namespace std;class TreeNode {public:int val;TreeNode *left, *right;TreeNode(int val) {this->val = val;this->left = this->right = NULL;}};void process(TreeNode *root, int target,vector<vector<int>>&  resvv,vector<int>& v,int sum){if(root == NULL) return;if(root->left == NULL && root->right == NULL ){//叶子结点if(sum+ root->val == target){ //找到了,加入resvvv.push_back(root->val);resvv.push_back(v);v.pop_back();}return;//到了叶子就要返回}v.push_back(root->val);sum += root->val;process(root->left, target,resvv,v,sum);process(root->right, target,resvv,v,sum);if(v.size() != 0)  v.pop_back();//返回时要弹出 最后的元素,不管是否找到。}vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {vector<vector<int>>  resvv;if(root == NULL) return resvv;vector<int> v;int sum=0;process(root,target,resvv,v,sum);return resvv;}int  main(){TreeNode* root=new TreeNode(1);//test1root->left=new TreeNode(2);root->left->left=new TreeNode(3);TreeNode* root2=new TreeNode(1);//test2root2->left=new TreeNode(2);root2->right=new TreeNode(4);root2->left->left=new TreeNode(2);root2->left->right=new TreeNode(5);binaryTreePathSum(root2,5);cout<< "maxPathSum(root)="<<endl;system("pause");}

注意:if(v.size() != 0)  v.pop_back();//返回时要弹出 最后的元素,不管是否找到。
0 0
原创粉丝点击