LeetCode //C - 104. Maximum Depth of Binary Tree

104. Maximum Depth of Binary Tree

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:

insert image description here

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, 1 0 4 10^4 104].
  • -100 <= Node.val <= 100

From: LeetCode
Link: 104. Maximum Depth of Binary Tree


Solution:

Ideas:

Main Function: maxDepth(struct TreeNode root)*
This function calculates the maximum depth of a binary tree recursively. Here’s how it works:

  1. Base Case: If the root node is NULL, the depth is 0. This means that you have reached a leaf node’s child (which doesn’t exist), so you return 0.

  2. Recursive Case: Otherwise, the function calculates the maximum depth of the left and right subtrees using recursive calls.

  3. Find Maximum and Return: Finally, the function finds the maximum of the two depths obtained above and adds 1 to it. The addition of 1 accounts for the depth of the current node.

Code:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int max(int a, int b) {
    
    
    return (a > b) ? a : b;
}

int maxDepth(struct TreeNode* root) {
    
    
    if (root == NULL) {
    
    
        return 0;
    }
    int leftDepth = maxDepth(root->left);
    int rightDepth = maxDepth(root->right);
    return max(leftDepth, rightDepth) + 1;
}

Guess you like

Origin blog.csdn.net/navicheung/article/details/132646117