题目描述: 二叉树的所有路径
给定一个二叉树,返回从根节点到叶节点的所有路径。
例如,给定以下二叉树:
1 / \ 2 3 \ 5
所有根到叶路径是:
["1->2->5", "1->3"]
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> vs;
if(root == NULL) return vs;
string s;
f(vs, s, root);
return vs;
}
bool f(vector<string>& v,string s, TreeNode* root) {
if(root == NULL) return true;
if(s.empty()) s += to_string(root->val);
else s += "->" + to_string(root->val);
bool a, b;
a = f(v, s, root->left);
b = f(v, s, root->right);
if(a&&b) v.push_back(s);
return false;
}
};