Post

LeetCode 104. Maximum Depth of Binary Tree

LeetCode 104. Maximum Depth of Binary Tree

LeetCode 104. Maximum Depth of Binary Tree

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

Matter

You are given the root of a binary tree.

Return the depth of the tree, defined as the number of nodes along the longest path from the root down to any leaf node.


Example.

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

Output:
3


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

Output:
2


Constraints

0 <= number of nodes <= $10^4$

-$100$ <= Node.val <= $100$


Problem analysis

The depth of a binary tree depends on the depth of its subtrees.

For each node:

  • the depth is 1 + max(left subtree depth, right subtree depth)

This naturally leads to a recursive solution.


Solution

DFS (Recursive)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution 
{
public:
    int maxDepth(TreeNode* root) 
    {
        int i32Depth = 1;
        int i32LeftDepth = 0;
        int i32RightDepth = 0;

        do
        {
            if(!root)
            {
                i32Depth = 0;
                break;
            }

            i32LeftDepth = maxDepth(root->left);
            i32RightDepth = maxDepth(root->right);
        } 
        while (false);

        return i32Depth + std::max(i32LeftDepth, i32RightDepth);
    }
};

should revise more! Remember!

This post is licensed under CC BY 4.0 by the author.