less than 1 minute read

ProblemPermalink

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.

Example 1:

image

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:

Input: root = [1,null,2]
Output: 2

Constraints:

  • The number of nodes in the tree is in the range [0, 10^4].
  • -100 <= Node.val <= 100

SolutionPermalink

LogicPermalink

  1. 노드의 왼쪽 혹은 오른쪽 자식 노드가 있으면 깊이를 1추가한다.

  2. Root노드부터 1번 과정을 수행하여 전체 이진트리를 탐색하며 최고 깊이를 찾아낸다.

  3. 왼쪽과 오른쪽 자식 노드 모두 존재하지 않으면 탐색을 종료하고 최고 깊이를 반환한다.

    CodePermalink

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

Categories:

Updated:

Leave a comment