题解 | #二叉树的最大深度#
二叉树的最大深度
https://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73
C语言
void recursion(struct TreeNode* node, int *maxDepth){
static int tmpDepth = 1; //初始化当前深度为1,根节点
if(*maxDepth < tmpDepth) *maxDepth = tmpDepth; //如果当前深度大于最大深度,则更新最大深度
if(!node->left && !node->right){ //如果该节点的左右子节点都不存在,则该节点是叶子节点,返回并深度-1
tmpDepth--;
return;
}
if(node->left) { //如果左子节点存在,深度+1并递归
tmpDepth++;
recursion(node->left, maxDepth);
}
if(node->right) {
tmpDepth++;
recursion(node->right, maxDepth);
}
tmpDepth--; //该节点左右子节点遍历完,深度-1并返回到上一次调用递归的位置。
}
int maxDepth(struct TreeNode* root ) {
// write code here
static int maxDepth = 0; //最大深度初始为0
if(root) recursion(root, &maxDepth); //根节点不存在则返回0
return maxDepth;
}