前言
LeetCode 的blabla Tree系列又一基础题,可配合 Minimum Depth of Binary Tree 一起练习。题解在此。
题目
https://leetcode.com/problems/maximum-depth-of-binary-tree/
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
分析
递归很容易就能做,见代码。
代码
Recursive solution:
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
if (root->left == NULL) return 1 + maxDepth(root->right);
if (root->right == NULL) return 1 + maxDepth(root->left);
return 1 + max(maxDepth(root->left),maxDepth(root->right));
}
};
稍微简化一下:
class Solution {
public:
int maxDepth(TreeNode* root) {
return root == NULL ? 0 : 1 + max(maxDepth(root->left),maxDepth(root->right));
}
};