일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- axios
- leetcode
- Context
- treenode
- BinaryTree
- c++
- map
- bit
- server
- nodeJS
- css
- 비트연산
- event
- Props
- queue
- count
- MySQL
- routes
- route
- React
- state
- DP
- array
- Navigation
- priority_queue
- UE5
- node.js
- Callback
- JSX
- component
- Today
- Total
우사미 코딩
[Leetcode] 110. Balanced Binary Tree 본문
1. 문제링크
Balanced Binary Tree - LeetCode
Can you solve this real interview question? Balanced Binary Tree - Given a binary tree, determine if it is height-balanced. Example 1: [https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg] Input: root = [3,9,20,null,null,15,7] Output: true Exam
leetcode.com
2. height-Balanced가 뭐지?
여기서 파란색 볼드를 클릭하면 height-balanced에 대한 설명이 나온다
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
즉 모든 노드에 대해서, 좌우subtress간의 높이 차가 1보다 작거나 같은 트리이다
위에서 root node인 3을 보면
왼쪽 subtree의 높이는 0 (9에서 더 뻗어나가는게 없으므로)
오른쪽 subtree의 높이는 1 (20이 오른쪽 subtree의 끝 노드가 아니므로)
1 - 0 = 1이니 height-balanced가 맞다
root node인 1에 대해서
왼쪽 subtree 높이 : 2, 오른쪽 subtree 높이 : 0 이므로
2 - 0 > 1이니 height-balanced가 아니다
3. Solution
class Solution {
public:
bool result = true;
int solve(TreeNode* root){
if(!root || result == false)
return 0;
int left = solve(root->left);
int right = solve(root->right);
if(abs(left - right) > 1){
result = false;
return 0;
}
return max(left, right) + 1;
}
bool isBalanced(TreeNode* root) {
solve(root);
return result;
}
};
'Leetcode' 카테고리의 다른 글
[Leetcode] 437. Path Sum III (0) | 2023.05.23 |
---|---|
[Leetcode] 543. Diameter of 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 |
[Leetcode] 48. Rotate Image - Matrix (0) | 2023.05.19 |