Problem
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
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
static int var = [](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
private:
vector<string> res;
public:
vector<string> binaryTreePaths(TreeNode* root) {
if(root==NULL)
return res;
translate("",root);
return res;
}
void translate(string path,TreeNode* node){
if(node->left==NULL && node->right==NULL){
res.push_back(path+to_string(node->val));
}
else{
if(node->left)
translate(path+to_string(node->val)+"->",node->left);
if(node->right)
translate(path+to_string(node->val)+"->",node->right);
}
}
};
网友评论