[LeetCode-104] Maximum Depth of Binary Tree(二叉树最大深度)

时间:2021-08-28 14:36:59

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.

【分析】
本题就是求解二叉树的深度:
递归解法:
(1)如果二叉树为空,二叉树的深度为0
(2)如果二叉树不为空,二叉树的深度 = max(左子树深度, 右子树深度) + 1

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/

int maxDepth(struct TreeNode* root) {
if(root == NULL) // 递归出口
return 0;
int depthLeft = maxDepth(root->left);
int depthRight = maxDepth(root->right);
return depthLeft > depthRight ? (depthLeft + 1) : (depthRight + 1);
}