思路:
- 看到树结构可以优先考虑递归,因为树本身就是一种递归结构,记住左、右孩子本身就是一颗树。
- 首先判断根节点是不是空值,如果为空,则返回0
- 如果根节点不为空,那么这棵树的最大深度就是1+左孩子或者右孩子的深度(取最大深度)
代码:
Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root==null)
return 0;
int left=maxDepth(root.left);
int right=maxDepth(root.right);
int child=Math.max(left,right);
return 1+child;
}
}
cpp
/**
* 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)
return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};