1.题目:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
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.
Note: A leaf is a node with no children.
2.代码:
/**
* 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 ldepth=maxDepth(root->left);
int rdepth=maxDepth(root->right);
if(ldepth>rdepth) //选取最大值+1返回上层;
return ldepth+1;
else
return rdepth+1;
}
3.知识点:
二叉树递归。