【LeetCode】257. Binary Tree Paths
问题描述
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
输出二叉树所有从根节点到叶子节点的路径。递归即可。
代码
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> r;
TreeNode* p = root;
if(p == 0) return r;
string s="";
char* str = new char[20];
sprintf(str, "%d", root->val);
s+=str;
if(p->left==0&&p->right==0) {
r.push_back(s);
return r;
}
vector<string> left = binaryTreePaths(p->left);
vector<string> right = binaryTreePaths(p->right);
s+="->";
for(int i=0;i<left.size();i++) {
r.push_back(s+left[i]);
}
for(int i=0;i<right.size();i++) {
r.push_back(s+right[i]);
}
return r;
}
};