Skip to content

Commit e077c9e

Browse files
committed
path in binary tree - Facebook
1 parent 10032da commit e077c9e

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

README.md

+19
Original file line numberDiff line numberDiff line change
@@ -629,3 +629,22 @@
629629

630630
#### Click [__*here*__](Solution/Day-109.cpp) for solution.
631631
---
632+
---
633+
### Problem 110
634+
##### This problem was asked by Facebook.
635+
##### Given a binary tree, `return all paths from the root to leaves`.
636+
##### For example, given the tree:
637+
```
638+
1
639+
/ \
640+
2 3
641+
/ \
642+
4 5
643+
644+
```
645+
##### Return `[[1, 2], [1, 3, 4], [1, 3, 5]]`.
646+
647+
#### Click [__*here*__](Solution/Day-109.cpp) for solution.
648+
#### Click [__*here*__](https://leetcode.com/problems/binary-tree-paths/) to visit [*LeetCode*](https://leetcode.com/) for this question.
649+
---
650+

Solution/Day-110.cpp

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
vector<string>res;
14+
void dfs(TreeNode* root , string path){
15+
if(root==nullptr){
16+
return;
17+
}
18+
if(path.size()>0){
19+
path+="->";
20+
}
21+
path+=to_string(root->val);
22+
if(root->left == nullptr && root->right == nullptr){
23+
res.emplace_back(path);
24+
return;
25+
}
26+
dfs(root->left , path);
27+
dfs(root->right , path);
28+
}
29+
public:
30+
vector<string> binaryTreePaths(TreeNode* root) {
31+
dfs(root , "");
32+
return res;
33+
}
34+
};
35+

0 commit comments

Comments
 (0)