이진 트리가 주어지면 트리의 가장 큰 깊이값을 찾는 문제입니다.
자식 노드로 계속 이동하며 깊이값을 찾는 문제이기에 DFS를 사용합니다.
/**
* 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) {}
* };
*/
int maxDepth(TreeNode* root) {
if (root == nullptr)
return 0;
// 자식노드가 있다면
int left = 0, right = 0;
if (root->left)
left = maxDepth(root->left);
if (root->right)
right = maxDepth(root->right);
// 현재 노드 1 + 자식 노드의 가장 큰 깊이값
return 1 + std::max(left, right);
}
'Algorithm 문제풀이 > Leetcode' 카테고리의 다른 글
(Easy - DFS) Leetcode - 226. Invert Binary Tree (0) | 2024.06.25 |
---|---|
(Easy - DFS) Leetcode - 572. Subtree of Another Tree (0) | 2024.06.25 |
(Easy - DFS) Leetcode - 543. Diameter of Binary Tree (0) | 2024.06.24 |
(Easy - DFS) Leetcode - 617. Merge Two Binary Trees (0) | 2024.06.24 |
(Easy - DFS) Leetcode - 112. Path Sum (0) | 2024.06.23 |