https://leetcode.com/problems/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"]$
/**
* 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) {
ans.clear();
if (!root) return ans;
dfs(root, "");
return ans;
}
private:
vector<string> ans;
void dfs(TreeNode *x, string ret) {
if (!x) return;
if (!x->left && !x->right) {
ans.push_back(ret + to_string(x->val));
return;
}
dfs(x->left, ret + to_string(x->val) + "->");
dfs(x->right, ret + to_string(x->val) + "->");
}
};
原文:http://www.cnblogs.com/GadyPu/p/5020623.html