일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
- node.js
- event
- queue
- Callback
- axios
- component
- MySQL
- treenode
- BinaryTree
- React
- routes
- JSX
- 비트연산
- map
- Context
- route
- css
- DP
- count
- c++
- bit
- Props
- state
- priority_queue
- server
- array
- Navigation
- nodeJS
- leetcode
- UE5
- Today
- Total
우사미 코딩
[Leetcode] 543. Diameter of Binary Tree 본문
1. 문제링크
Diameter of Binary Tree - LeetCode
Can you solve this real interview question? Diameter of Binary Tree - Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path
leetcode.com
- Diameter : 지름
binary tree에서 제일 긴 path의 길이를 구한다
이 path는 특정노드에 대해서 가장 왼쪽 edge node -> 오른쪽 edge 노드까지의 길이이다
2. Key point - 현재 노드의 maxLength를 리턴하고, maxDia는 매번 갱신한다
문제에서 path는 root노드를 pass하지 않아도 되는 조건이 있다.
1번 노드(빨강)의 longest path는 [6, 4, 2, 1, 3]이고 diameter는 4이다
2번 노드(노랑)의 longest path는 [6, 4, 2, 5, 7, 8]이고 diameter는 5이다
이 tree node에서 가장 긴 diameter를 구하는 문제이므로 정답은 5가 된다.
3. solution
class Solution {
public:
int maxDia = 0;
int getLength(TreeNode* root){
if(!root)
return 0;
int left = getLength(root->left);
int right = getLength(root->right);
maxDia = max(maxDia, left + right);
return max(left, right) + 1;
}
int diameterOfBinaryTree(TreeNode* root) {
getLength(root);
return maxDia;
}
};
'Leetcode' 카테고리의 다른 글
[Leetcode] 33. Search in Rotated Sorted Array - binary search (0) | 2023.05.23 |
---|---|
[Leetcode] 437. Path Sum III (0) | 2023.05.23 |
[Leetcode] 110. Balanced Binary Tree (0) | 2023.05.23 |
[Leetcode] 953. Verifying an Alien Dictionary - hash map (0) | 2023.05.22 |
[Leetcode] 148. Sort List (0) | 2023.05.19 |