问题:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
样例:
样例 1:
输入: tree = {} 输出: 0 样例解释: 空树的深度是0。
样例 2:
输入: tree = {1,2,3,#,#,4,5} 输出: 3 样例解释: 树表示如下,深度是3 1 / \ 2 3 / \ 4 5 它将被序列化为{1,2,3,#,#,4,5}
python:
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: An integer
"""
def maxDepth(self, root):
# write your code here
if root == None:
return 0
else:
lnum = self.maxDepth(root.left)
rnum = self.maxDepth(root.right)
return max(lnum,rnum)+1
C++:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxDepth(TreeNode * root) {
// write your code here
if(root == NULL)
{
return 0;
}else{
int lnum = maxDepth(root->left);
int rnum = maxDepth(root->right);
return max(lnum,rnum)+1;
}
}
};