输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
提示:节点总数 <= 10000
思路:
如果我们知道了左子树和右子树的最大深度leftMax和rightMax,那么该二叉树的最大深度即为
max(leftMax,rightMax)+1
在计算当前二叉树的最大深度时,可以先递归计算出其左子树和右子树的最大深度,递归在访问到空节点时退出。
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
int leftMax = maxDepth(root.left);
int rightMax = maxDepth(root.right);
return Math.max(leftMax,rightMax)+1;
}
}
更简洁一些:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int calculateDepth(struct TreeNode* root) {
return root==NULL?0:fmax(calculateDepth(root->left),calculateDepth(root->right))+1;
}