贴原题:
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.
解析:
本题是要求二叉树的深度。这应该算是数据结构最基础的题目了。
C代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root) {
int l_depth=0, r_depth=0;
if(root!=NULL)//根节点非空则继续向下遍历
{
l_depth=maxDepth(root->left)+1;//深度+1
r_depth=maxDepth(root->right)+1;
}
return l_depth>r_depth?l_depth:r_depth;//取左右最大值
}