[leetcode] Maximum Depth of Binary Tree

jun·2021년 4월 4일
0
post-thumbnail

유의할점

풀이

dfs 탐색하면서 최대값을 찾는다.

코드

Java : 내가 짠 코드


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

Java : 누가봐도 이게 정답..

public int maxDepth(TreeNode root) {
        if(root==null){
            return 0;
        }
        return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
    }
profile
Computer Science / Algorithm / Project / TIL

0개의 댓글