All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0101_0200.s0104_maximum_depth_of_binary_tree.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0101_0200.s0104_maximum_depth_of_binary_tree;

// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Depth_First_Search #Breadth_First_Search
// #Tree #Binary_Tree #Data_Structure_I_Day_11_Tree
// #Programming_Skills_I_Day_10_Linked_List_and_Tree #Udemy_Tree_Stack_Queue
// #Big_O_Time_O(N)_Space_O(H) #2022_06_22_Time_0_ms_(100.00%)_Space_42.9_MB_(67.03%)

import com_github_leetcode.TreeNode;

/*
 * 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;
 *     }
 * }
 */
/**
 * 104 - Maximum Depth of Binary Tree\.
 *
 * Easy
 *
 * 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:**
 *
 * ![](https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg)
 *
 * **Input:** root = [3,9,20,null,null,15,7]
 *
 * **Output:** 3 
 *
 * **Example 2:**
 *
 * **Input:** root = [1,null,2]
 *
 * **Output:** 2 
 *
 * **Example 3:**
 *
 * **Input:** root = []
 *
 * **Output:** 0 
 *
 * **Example 4:**
 *
 * **Input:** root = [0]
 *
 * **Output:** 1 
 *
 * **Constraints:**
 *
 * *   The number of nodes in the tree is in the range [0, 104].
 * *   `-100 <= Node.val <= 100`
**/
public class Solution {
    public int maxDepth(TreeNode root) {
        return findDepth(root, 0);
    }

    private int findDepth(TreeNode node, int currentDepth) {
        if (node == null) {
            return 0;
        }
        currentDepth++;
        return 1
                + Math.max(findDepth(node.left, currentDepth), findDepth(node.right, currentDepth));
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy