Question :
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"]
Solution :
主要要做的就是遍历一棵树,不过要记录遍历时候遇到的值,这里使用dfs来完成遍历并记录沿途的值。
/**
* 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> ret;
if(root == NULL) {
return ret;
}
string root_val = to_string(root->val);
dfs(ret, root, root_val);
return ret;
}
void dfs(vector<string> & v, TreeNode* root, string str){
if(root->left == NULL && root->right == NULL){
v.push_back(str);
return;
}
if(root->left != NULL) {
string val_str = str + "->" + to_string(root->left->val);
dfs(v, root->left, val_str);
}
if(root->right != NULL) {
string val_str = str + "->" + to_string(root->right->val);
dfs(v, root->right, val_str);
}
}
};