LeetCode_Study_Plan/Programming Skills

104. Maximum Depth of Binary Tree java

개발하는루루 2022. 9. 24. 14:26

https://leetcode.com/problems/maximum-depth-of-binary-tree/?envType=study-plan&id=programming-skills-i 

 

Maximum Depth of Binary Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

/**
 * 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 solve(TreeNode node, int depth) {
        if(node == null)
            return depth;
        return Math.max(solve(node.left, depth+1), solve(node.right, depth+1));
    }
    public int maxDepth(TreeNode root) {
        int res = solve(root, 0);
        return res;
    }
}

이건 한참을 생각해도 방법을 모르겠어서 답지를 찾아봤다. 

 

 

풀이 방법


 

1. 루트 노드부터 탐색을 시작한다.

2. 현재 노드의 왼쪽 노드와 오른쪽 노드를 탐색하여, 함수를 호출할 때마다 depth를 1 증가시켜 depth의 최대 값을 구한다.

3. 노드가 null일 경우, depth 값을 반환한다.

 

 

 

재귀적 사고는 아직도 어렵다..큰일났구만 ㅠㅠ