Leetcode 104. Maximum Depth of Binary Tree
Leetcode Problem 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.
To determine the maximum depth of a binary tree, we can use Depth First Search (DFS). Specifically, a recursive approach is efficient and intuitive:
nullptr
, return 0.Here’s the implementation of the above strategy in C++:
#include <iostream>
// Definition for a binary tree node.
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) {}
};
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return 1 + std::max(leftDepth, rightDepth);
}
};
int main() {
// Create a sample binary tree:
// 3
// / \
// 9 20
// / \
// 15 7
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(9);
root->right = new TreeNode(20);
root->right->left = new TreeNode(15);
root->right->right = new TreeNode(7);
Solution solution;
std::cout << "Maximum Depth of the binary tree: " << solution.maxDepth(root) << std::endl; // Output: 3
// Clean up memory (optional as main is going to exit, but good for practice)
delete root->right->right;
delete root->right->left;
delete root->right;
delete root->left;
delete root;
return 0;
}
The time complexity of this algorithm is (O(N)), where (N) is the number of nodes in the binary tree. The function visits each node exactly once.
The space complexity is (O(d)), where (d) is the maximum depth of the tree. This is due to the recursion stack. In the worst-case scenario (a completely unbalanced tree), the depth could be equal to (N). In a balanced tree, the depth would be (O(\log N)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?