二叉树的路径和---递归返回时要弹出向量尾的元素,不管是否找到。
来源:互联网 发布: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
- 二叉树的路径和---递归返回时要弹出向量尾的元素,不管是否找到。
- leetcode_112. Path Sum 二叉树路径求和,判断是否存在路径和为某个值的路径,深度遍历,递归的return
- 二叉树遍历的应用(路径和问题,判断是否是二叉搜索树,判断是否是二叉平衡树)
- java二叉树漫谈--二叉树的递归便利和路径
- 在二叉树中找到累加和为指定值的最长路径长度
- 二叉树系列---找到累加和为指定值的最长路径长度
- 在二叉树中找到累加和为指定值的最长路径长度
- 在二叉树中找到累加和为指定值的最长路径长度
- 二叉树的递归和非递归
- 二叉树的递归和非递归
- 判断二叉树是否平衡以及二叉树的路径和
- 二叉树问题---在二叉树中找到累加和为指定值的最长路径长度
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- jquery字符串转日期类型
- Swift 根据文字字体的大小得到size
- web前端面试题及答案 html篇 下
- thinkphp 操作mysql遇到的坑。
- Struts2框架的构建
- 二叉树的路径和---递归返回时要弹出向量尾的元素,不管是否找到。
- centos 安装postgreSQL
- 单例模式(Singleton)
- 百度地图定位
- FZU 2236 第十四个目标 (线段树)
- sql字符操作 split
- Apache 防盗链配置详解介绍
- java 类的加载和反射介绍
- Spring mvc 入门搭建一