题目描述:
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
给定一个二叉树,返回从根节点到叶节点的所有路径。显然是利用递归,从根节点开始遍历,每次遍历的节点都加入遍历路径中,当遍历到叶节点则递归结束。
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<vector<int>> v;
binaryTreePaths_recur(root,path,v);
vector<string> result;
for(int i=0;i<v.size();i++)
{
if(v[i].size()==1) result.push_back(to_string(v[i][0]));
else
{
string s;
for(int j=0;j<v[i].size();j++)
{
if(j==v[i].size()-1) s+=to_string(v[i][j]);
else s+=to_string(v[i][j])+"->";
}
result.push_back(s);
}
}
return result;
}
void binaryTreePaths_recur(TreeNode* root, vector<int> path, vector<vector<int>>& result)
{
if(root==NULL) return;
path.push_back(root->val);
if(root->left==NULL&&root->right==NULL)
{
result.push_back(path);
return;
}
else
{
binaryTreePaths_recur(root->left,path,result);
binaryTreePaths_recur(root->right,path,result);
}
}
};