반응형
LV. Easy 😎
https://leetcode.com/problems/maximum-depth-of-binary-tree/
문제
Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2
Constraints:
- The number of nodes in the tree is in the range [0, 104].
- -100 <= Node.val <= 100
문제 해결법
오른쪽 왼쪽으로 갈 때마다 깊이를 +1 해주고 ans과 비교해서 max 값을 저장해주면 끝!
해결 코드
class Solution {
private:
int ans;
void node(TreeNode* root, int deep) {
ans = max(ans, deep);
if (!root)
return ;
else {
node(root->left, deep + 1);
node(root->right, deep + 1);
}
}
public:
int maxDepth(TreeNode* root) {
ans = 0;
node(root, 0);
return ans;
}
};
728x90
'Computer Science > 알고리즘' 카테고리의 다른 글
leetcode 24) Swap Nodes in Pairs (0) | 2022.02.16 |
---|---|
leetcode 136) Single Number (0) | 2022.02.15 |
leetcode 78) Subsets (0) | 2022.02.13 |
leetcode 127) Word Ladder (0) | 2022.02.12 |
leetcode 560) Subarray Sum Equals K (0) | 2022.02.11 |
댓글