Skip to content

Commit 9a254a7

Browse files
committed
풀이: 릿코드.1022.Sum of Root To Leaf Binary Numbers
?: DFS를 이용해 풀이
1 parent 74a9193 commit 9a254a7

3 files changed

Lines changed: 116 additions & 0 deletions

File tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# 1022. Sum of Root To Leaf Binary Numbers
2+
3+
[링크](https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/description/)
4+
5+
| 난이도 |
6+
| :----: |
7+
| Easy |
8+
9+
## 설계
10+
11+
### 시간 복잡도
12+
13+
트리의 노드의 수를 N, 높이를 H라 하자.
14+
15+
DFS를 이용해 모든 노드를 방문할 경우 O(N)의 시간 복잡도를 사용한다.
16+
17+
### 공간 복잡도
18+
19+
DFS를 사용할 경우 O(H)의 공간 복잡도를 사용한다.
20+
21+
### DFS
22+
23+
| 내 코드 (ms) | 시간 복잡도 | 공간 복잡도 |
24+
| :----------: | :---------: | :---------: |
25+
| 0 | O(N) | O(H) |
26+
27+
DFS를 이용해 리프노드에서 루트노드까지의 비용을 계산한다.
28+
29+
```cpp
30+
int recursive(TreeNode* node, int val) {
31+
int cur = val * 2 + node->val;
32+
int leftVal = 0, rightVal = 0;
33+
if (node->left) {
34+
leftVal = recursive(node->left, cur);
35+
}
36+
if (node->right) {
37+
rightVal = recursive(node->right, cur);
38+
}
39+
40+
if (!node->left && !node->right) {
41+
return cur;
42+
}
43+
return leftVal + rightVal;
44+
}
45+
46+
int sumRootToLeaf(TreeNode* root) {
47+
if (!root) return 0;
48+
49+
return recursive(root, 0);
50+
}
51+
```
52+
53+
## 고생한 점
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#include <algorithm>
2+
#include <climits>
3+
#include <cmath>
4+
#include <cstring>
5+
#include <functional>
6+
#include <iostream>
7+
#include <map>
8+
#include <numeric>
9+
#include <queue>
10+
#include <set>
11+
#include <stack>
12+
#include <string>
13+
#include <unordered_map>
14+
#include <unordered_set>
15+
#include <vector>
16+
17+
using namespace std;
18+
19+
struct TreeNode {
20+
int val;
21+
TreeNode* left;
22+
TreeNode* right;
23+
TreeNode() : val(0), left(nullptr), right(nullptr) {}
24+
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
25+
TreeNode(int x, TreeNode* left, TreeNode* right)
26+
: val(x), left(left), right(right) {}
27+
};
28+
29+
// DFS
30+
// time : O(N)
31+
// space : O(H)
32+
class Solution {
33+
private:
34+
int recursive(TreeNode* node, int val) {
35+
int cur = val * 2 + node->val;
36+
int leftVal = 0, rightVal = 0;
37+
if (node->left) {
38+
leftVal = recursive(node->left, cur);
39+
}
40+
if (node->right) {
41+
rightVal = recursive(node->right, cur);
42+
}
43+
44+
if (!node->left && !node->right) {
45+
return cur;
46+
}
47+
return leftVal + rightVal;
48+
}
49+
50+
public:
51+
int sumRootToLeaf(TreeNode* root) {
52+
if (!root) return 0;
53+
54+
return recursive(root, 0);
55+
}
56+
};
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Input: root = [1,0,1,0,1,0,1]
2+
Output: 22
3+
4+
===
5+
6+
Input: root = [0]
7+
Output: 0

0 commit comments

Comments
 (0)