给一棵二叉树,找出从根节点到叶子节点的所有路径。
您在真实的面试中是否遇到过这个题? Yes
样例
给出下面这棵二叉树:
1
/ \
2 3
\
5
所有根到叶子的路径为:
[
"1->2->5",
"1->3"
]
/**
* 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> binaryTreePaths(TreeNode* root) {
// Write your code here
vector<string> results;
vector<int> temp;
if(root==NULL) {
return results;
}
preTravel(root,temp,results);
return results;
}
void preTravel(TreeNode* root,vector<int> &temp,vector<string> &results) {
temp.push_back(root->val);
if(root->left == NULL&&root->right == NULL) {
string str;
for(auto i: temp){
str += to_string(i) + "->";
}
str = str.substr(0,str.size()-2);
results.push_back(str);
}
if (root->left != NULL) {
preTravel(root->left,temp,results);
}
if (root->right != NULL) {
preTravel(root->right,temp,results);
}
temp.pop_back();
}
};