250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code c++)Maximum Depth of Binary Tree 본문
728x90
반응형
104. Maximum Depth of Binary Tree
Easy
4338102Add to ListShare
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
Example 3:
Input: root = [] Output: 0
Example 4:
Input: root = [0] Output: 1
Constraints:
- The number of nodes in the tree is in the range [0, 104].
- -100 <= Node.val <= 100
이진 트리의 depth를 구하면 된다.
root가 널이 아닌 경우 dfs() 함수를 통해 depth를 구한다.
left와 right의 depth를 구하여, 현재 depth와 left, right의 depth 중 가장 큰 값을 리턴하면 된다.
/**
* 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 dfs(TreeNode * node, int current){
int left = 0;
int right = 0;
if(node->left != NULL){
left = dfs(node->left, current + 1);
}
if(node->right != NULL){
right = dfs(node->right, current + 1);
}
current = max(current, max(left, right));
return current;
}
int maxDepth(TreeNode* root) {
int answer = 0;
if(root != NULL){
answer = dfs(root, 1);
}
return answer;
}
};
728x90
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code c++)Convert Sorted Array to Binary Search Tree (0) | 2021.07.14 |
---|---|
(Leet Code c++)Concatenation of Array (0) | 2021.07.14 |
(Leet Code c++)Symmetric Tree (0) | 2021.07.13 |
(Leet Code c++)Same Tree (0) | 2021.07.13 |
(Leet Code c++)Merge Sorted Array (0) | 2021.07.13 |