104. 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.
二、输入输出
三、解题思路
递归
- 用递归两行代码就可以搞定。如果root为空就返回0,否则就从左子树和右字树的深度中取较大的值,然后加上一作为最终结果返回。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr)return 0;
return 1+std::max(maxDepth(root->left), maxDepth(root->right));
}
};