문제 URL : https://leetcode.com/problems/binary-tree-paths/
문제접근법 : 이진트리의 루트에서 리프토드까지 있는 경로를모두 출력하라는 겁니다.
dfs를 이용하면 되겠고 리프노드라는건 양쪽 왼쪽자식과 오른쪽자식이 없는것을 뜻하니 없을때는 ->를 안붙여주면되는거니 어렵지 않은문제입니다.
소스코드 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
//By 콩순이냉장고
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
dfs(root,"",res);
return res;
}
void dfs(TreeNode* root,string s,vector<string> &res){
if(!root->left&&!root->right){
res.push_back(s+to_string(root->val));
return;
}
if(root->left)
dfs(root->left,s+to_string(root->val)+"->",res);
if(root->right)
dfs(root->right,s+to_string(root->val)+"->",res);
}
};
|
cs |
궁금한점 혹은 모르는점 어떤 질문이든 댓글은 언제나 환영입니다.
'LeetCode' 카테고리의 다른 글
LeetCode 74 Search a 2D Matrix (0) | 2021.11.17 |
---|---|
LeetCode 112 Path Sum (0) | 2021.11.14 |
LeetCode 103. Binary Tree Zigzag Level Order Traversal (0) | 2021.08.03 |
LeetCode 686. Repeated String Match (0) | 2021.07.31 |
LeetCode 572. Subtree of Another Tree (0) | 2021.07.31 |