[leetcode #104] Maximum Depth of Binary Tree

Seongyeol Shin·2022년 2월 14일
0

leetcode

목록 보기
150/196
post-thumbnail

Problem

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:

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⁴].
・ -100 <= Node.val <= 100

Idea

주어진 Tree의 높이를 구하는 문제다.

Tree를 탐색하면서 자식 노드가 나올 때마다 depth를 1씩 올린다. 왼쪽 자식 노드와 오른쪽 자식 노드를 재귀적으로 탐색하면서 depth가 더 큰 값을 선택하면 된다.

Tree가 알고리즘에서 자주 출제되는 주제이므로 반드시 쉽게 풀 수 있어야 한다.

Solution

/**
 * 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 traverseTree(root, 0);
    }

    private int traverseTree(TreeNode node, int depth) {
        if (node == null) {
            return depth;
        }

        return Math.max(traverseTree(node.left, depth), traverseTree(node.right, depth)) + 1;
    }
}

Reference

https://leetcode.com/problems/maximum-depth-of-binary-tree/

profile
서버개발자 토모입니다

0개의 댓글