How to solve Leetcode 104. Maximum Depth of Binary Tree
A simple recursive algorithm with a binary tree

Hi! My name is Nhut Nguyen. I am a software engineer and a writer in Copenhagen, Denmark.
Learn more about me at nhutnguyen.com
Search for a command to run...
A simple recursive algorithm with a binary tree

Hi! My name is Nhut Nguyen. I am a software engineer and a writer in Copenhagen, Denmark.
Learn more about me at nhutnguyen.com
No comments yet. Be the first to comment.
A simple example of using C++ switch

Two dynamic programming techniques to solve Leetcode 120. Triangle. One has space complexity O(n^2). The other is O(n).

An example of using a sliding window approach and an unordered map to track character positions

A simple C++ solution to Leetcode 1695. Maximum Erasure Value using a sliding window approach and prefix sums.

Strategies to avoid them will help you excel in your following technical interview

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.

Input: root = [3,9,20,null,null,15,7]
Output: 3
Input: root = [1,null,2]
Output: 2
The number of nodes in the tree is in the range [0, 10^4].
-100 <= Node.val <= 100.
You have the following recursive relationship between the root and its children.
maxDepth(root) = max(maxDepth(root->left), maxDepth(root->right))
#include <iostream>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
int maxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
return 1 + std::max(maxDepth(root->left), maxDepth(root->right));
}
int main() {
TreeNode fifteen(15);
TreeNode seven(7);
TreeNode twenty(20, &fifteen, &seven);
TreeNode nine(9);
TreeNode three(3, &nine, &twenty);
std::cout << maxDepth(&three) << std::endl;
TreeNode two(2);
TreeNode one(1, nullptr, &two);
std::cout << maxDepth(&one) << std::endl;
}
Output:
3
2
Runtime: O(N), where N is the number of nodes.
Extra space: O(N).