1、问题概述:给一个二叉树,返回最大深度(深度:根节点到最远子节点路径上的节点数)
2、分析:
(1)判断是否为空树
(2)左子数深度为m
(3)右子树深度为n
(4)左右字数进行比较:m>n ? m+1 : n+1
3、代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
法1:
int maxDepth(struct TreeNode* root) {
int max=0; // 存放子树的深度
int leftMax=0;
int rightMax=0;
if(root!=NULL){
max++; // 当root不为空时,深度先加1
leftMax=maxDepth(root->left); // 左子树深度
rightMax=maxDepth(root->right); // 右子树深度
max+=leftMax>rightMax?leftMax:rightMax; // 当前字数的深度
}
return max;
}
-----------------------------------------------------------------------------------------
法2:
int maxDepth(struct TreeNode* root) {
int max=0; // 存放子树的深度
if(!root) return max;
int leftMax=maxDepth(root->left);
int rightMax=maxDepth(root->right);
if(!leftMax){
max=rightMax+1;
}else if(!rightMax){
max=leftMax+1;
}else{
max=leftMax > rightMax ? leftMax+1 : rightMax+1;
}
return max;
}