[LeetCode][Java] Maximum Depth of Binary Tree

최지수·2022년 3월 9일
0

Algorithm

목록 보기
65/77
post-thumbnail

문제

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.

제한사항

  • The number of nodes in the tree is in the range [0, 10410^4].
  • -100 \leq Node.val \leq 100

접근

가볍게~ 재귀 접근으로 풀었어요. leftright만 비교해도 되고, 한번 재귀 접근할 때마다 +1 하는 식으로 접근하니 해결되었어요.

답안

/**
 * 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 getDepth(root);
    }
    
    private int getDepth(TreeNode node){
        if(null == node)
            return 0;
        
        return Math.max(getDepth(node.left) + 1, getDepth(node.right) + 1);
    }
}
profile
#행복 #도전 #지속성

0개의 댓글