본문 바로가기

알고리즘/LeetCode

[LeetCode/104/Java]Maximum Depth of Binary Tree

[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
반응형