问题描述:
给一棵二叉树,找出从根节点到叶子节点的所有路径。
样例:
给出下面这棵二叉树:
1
/ \
2 3
\
5
所有根到叶子的路径为:
[
"1->2->5",
"1->3"
]
解题思路:
用两个全局变量的string类型的向量,一个存储数据 一个用来存路径,存数据的时候将整数类型转化成string类型,找到叶子节点就将路径存储到数组中,递归每返回一层就删掉一个元素。
代码:
/**
* 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
*/
vector<string>Path;
vector<string>path;
void int2str(const int &int_temp,string &string_temp)
{
stringstream stream;
stream<<int_temp;
string_temp=stream.str(); //此处也可以用 stream>>string_temp
}
void BinaryTreePaths(TreeNode* root) {
if (root== NULL)return;
string b;
int2str(root->val,b);
path.push_back(b);
BinaryTreePaths(root->left);
BinaryTreePaths(root->right);
if (root->left==NULL&&root->right==NULL) {
string a=path[0];
for (int i=1; i< path.size(); i++) {
a=a+"->"+path[i];
}
Path.push_back(a);
}
path.pop_back();
}
vector<string> binaryTreePaths(TreeNode* root) {
// Write your code here
if(root==NULL)return Path;
BinaryTreePaths(root);
return Path;
}
};
感想:
/**
* 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
*/
vector<string>Path;
vector<string>path;
void int2str(const int &int_temp,string &string_temp)
{
stringstream stream;
stream<<int_temp;
string_temp=stream.str(); //此处也可以用 stream>>string_temp
}
void BinaryTreePaths(TreeNode* root) {
if (root== NULL)return;
string b;
int2str(root->val,b);
path.push_back(b);
BinaryTreePaths(root->left);
BinaryTreePaths(root->right);
if (root->left==NULL&&root->right==NULL) {
string a=path[0];
for (int i=1; i< path.size(); i++) {
a=a+"->"+path[i];
}
Path.push_back(a);
}
path.pop_back();
}
vector<string> binaryTreePaths(TreeNode* root) {
// Write your code here
if(root==NULL)return Path;
BinaryTreePaths(root);
return Path;
}
};
还是借助遍历进行一些其他的操作。