[LeetCode] 104 - Maximum Depth of Binary Tree
문제
- 링크: https://leetcode.com/problems/maximum-depth-of-binary-tree
- 난이도: Easy
- 태그: 트리, 깊이 우선 탐색, 너비 우선 탐색, 이진 트리
- 결과:
Time: 0 ms (100%), Space: 18.90 MB (96.48%)
풀이
/**
* 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:
int maxDepth(TreeNode* root) {
return solve(root, 0);
}
int solve(TreeNode* root, int depth)
{
if (root == nullptr)
{
return depth;
}
int l = solve(root->left, depth);
int r = solve(root->right, depth);
return max(l, r) + 1;
}
};
이진 트리이므로 왼쪽, 오른쪽 자식을 재귀로 타고 들어가면서 깊이를 재면 된다.
댓글남기기