[LeetCode/104/Java]Maximum Depth of Binary Tree
풀이
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
return maxDepth(root, 0);
}
public int maxDepth(TreeNode root, int dept) {
if(root == null) return dept;
if(root.left == null && root.right == null) return dept + 1;
int left = dept;
int right = dept;
if(root.left != null) left = maxDepth(root.left, dept + 1);
if(root.right != null) right = maxDepth(root.right, dept + 1);
return left > right ? left : right;
}
}
후기
최대 깊이를 구하는 알고리즘입니다.
깊이우선 탐색(DFS)를 이용해서 문제를 풀었습니다.
time complexity O(N)
space complexity O(N)
728x90
반응형
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode/111/Java]Minimum Depth of Binary Tree (0) | 2022.06.05 |
---|---|
[LeetCode/110/Java]Balanced Binary Tree (0) | 2022.06.05 |
[LeetCode/101/Java]Symmetric Tree (0) | 2022.06.05 |
[LeetCode/100/Java]Same Tree (0) | 2022.06.05 |
[LeetCode/98/Java]Validate Binary Search Tree (0) | 2022.06.05 |