二叉树的路径和
来源:互联网 发布:应聘软件测试自我介绍 编辑:程序博客网 时间:2024/06/05 22:50
题目描述:
二叉树的路径和
给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值
的路径。
一个有效的路径,指的是从根节点到叶节点的路径。
给定一个二叉树,和 目标值 = 5
:
1 / \ 2 4 / \ 2 3
返回:
[ [1, 2, 2], [1, 4]]
遍历二叉树,然后用一维数组记录从根节点到叶子节点的路径,然后将每条路径上节点值的和已知的比较,如果相等,将此数组添加另一个数组就行了。
实现代码:
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) {
// Write your code here
vector<vector<int> > paths;
vector<int> path;
if(root==NULL) return paths;
else {
sum(root,path,paths,target);
return paths;
}
}
void sum(TreeNode *root,vector<int> p,vector<vector<int> >&q ,int target)
{ p.push_back(root->val);
vector<int>::iterator itp;
if(root->left==NULL&&root->right==NULL)
{
int n=0;
for(itp=p.begin();itp!=p.end();itp++)
{
n=n+*itp;
}
if(n==target){
q.push_back(p);
}
}
if(root->left!=NULL) sum(root->left,p,q,target);
if(root->right!=NULL) sum(root->right,p,q,target);
}
};
感想:这题首先得分清局部变量和全局变量,思路能想到,就是在处理细节的时候,局部变量与全局变量要搞清楚!
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 【disconf】环境搭建
- HashMap与HashTable
- 菱形内的计数
- 第二届蓝桥杯 中奖计算
- SharedPreferences.getInt() 出现ClassCastException错误
- 二叉树的路径和
- vi文本编辑器
- 部署javaweb到云服务器上
- 最小化安装centos7.3+redmine3.3.3+passenger
- FFmpeg 命令行推流 传视频到组播①
- listview 加标题
- MySQL
- poj1456 贪心
- HTTP实现断点续传简单实例