알고리즘 문제풀이/leetcode
[leetcode 104] Maximum Depth of Binary Tree
m2162003
2020. 10. 23. 16:15
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
return 3
문제 풀이:
-난이도 easy
recursion 사용
현재 노드가 nullptr이면 0을 리턴
그렇지 않으면 1씩 더해서 리턴한다. 이 때 왼쪽과 오른쪽 중 큰 값에 1을 더해서 리턴한다.
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root){
return 0;
}
return 1+ max(maxDepth(root->left), maxDepth(root->right));
}
};