很久之前写过有关二叉树的所有路径,今天刷lintcode发现自己忘记了,还是找个地方自己存一下,以后方便自己学习;
递归出口:最后遍历的节点是叶子节点;
递归条件:如果子树存在则继续递归;
代码:
/**
* 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 the binary tree
* @return: all root-to-leaf paths
*/
void allpath(TreeNode *root,vector<string> &res,vector<string> &temp)
{
temp.push_back(to_string(root->val));
if(root->left==nullptr&&root->right==nullptr)
{
string s;
string c="->";
for(int i=0;i<temp.size()-1;i++)
s=s+temp[i]+c;
s+=temp.back();
res.push_back(s);
}
if(root->left)
allpath(root->left,res,temp);
if(root->right)
allpath(root->right,res,temp);
temp.pop_back();
}
vector<string> binaryTreePaths(TreeNode * root) {
// write your code here
vector<string> res;
vector<string> temp;
if(root==nullptr)
return res;
allpath(root,res,temp);
return res;
}
};
此题和上一题类似,增加了遍历至叶子时,计算此时路径和,和目标值比较;
递归出口:遍历至叶子节点
代码:
/**
* 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
*/
void trace(TreeNode * root, vector<vector<int> > &res, vector<int> &temp, int target)
{
if(root==nullptr)
return;
temp.push_back(root->val);
int sum=accumulate(temp.begin(),temp.end(),0);
if(root->left==nullptr&&root->right==nullptr&&sum==target)
res.push_back(temp);
if(root->left)
trace(root->left,res,temp,target);
if(root->right)
trace(root->right,res,temp,target);
temp.pop_back();
}
vector<vector<int>> binaryTreePathSum(TreeNode * root, int target) {
// write your code here
vector<vector<int> > res;
vector<int> temp;
trace(root,res,temp,target);
return res;
}
};