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.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its depth = 3.
给定二叉树,找到它的最大深度。
最大深度是从根节点到最远叶节点的最长路径上的节点数。
注意: 叶子是没有子节点的节点。
思路
1.如果根为空,则返回深度为0;
2.递归遍历左右子树,没找到一个左孩子或右孩子深度就加一
3.返回最大的深度;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root) {
if(!root) return 0;
int leftdepth = maxDepth(root->left);
int rightdepth = maxDepth(root->right);
return leftdepth > rightdepth ? leftdepth + 1 :rightdepth + 1;
}