二叉树的路径和
来源:互联网 发布:哪个编程语言最难学 编辑:程序博客网 时间:2024/06/05 19:35
题目:
给一棵二叉树,找出从根节点到叶子节点的所有路径。
给出下面这棵二叉树:
1 / \2 3 \ 5
所有根到叶子的路径为:
[ "1->2->5", "1->3"]
思路:这个和后边那个二叉树的所有路径稍有不同,就是在找出路径里节点和判断是否等于target,如果等于就将这个路径插入到ss中。
代码:
/**
* 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) {
// Write your code here
vector<vector<int>> ss;
vector<int>s;
//vector<int>t;
if(root==NULL) return ss;
//s[0]=root->val;
s.push_back(root->val);
all(root,ss,s,target);
return ss;
}
void all(TreeNode *root,vector<vector<int>>&ss,vector<int>s,int target){
vector<int>t;
if(root->left==NULL&&root->right==NULL){
int k=0;
for(int i=0;i<=s.size()-1;i++)
{ k=k+s[i];
}
if(k==target)
{ss.push_back(s);}
return;
}
t=s;
if(root->left!=NULL)
{s.push_back(root->left->val);all(root->left,ss,s,target);}
if(root->right!=NULL)
{t.push_back(root->right->val);all(root->right,ss,t,target);}
}
};
感想:我完成之后总是run time error,后来才想起来这个错误出现的原因,就把s[0]=root->val;改成了s.push_back(root->val);还有第41行,必须要先改变s,才能执行后面的,而不能将这两个容在一块。
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- POJ 3067 Japan (树状数组求逆序数---经典)
- lintcode/leetcode由易至难第1题:返回第n个斐波那契数
- ch追妹 博弈
- 读书笔记——简介
- Nginx开发从入门到精通
- 二叉树的路径和
- js调整浏览器窗口大小
- zoj 3962 Seven Segment Display 数位dp
- LeetCode #455: Assign Cookies
- 二十、npm,cnpm,browser-sync,gulp使用简介
- XML Schema 及其文件.xsd
- 关于Asm.js的一些基本介绍和它的实现
- 优先使用注解,慎用枚举
- c语言(完数)