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.
求二叉树的最大深度,如果根结点为空,返回0,否则返回左右结点的深度的较大值
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
else{
int leftDepth=1+maxDepth(root.left);
int rightDepth=1+maxDepth(root.right);
return Math.max(leftDepth,rightDepth);
}
}
}
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if(root==None):
return 0;
else:
leftDepth=1+self.maxDepth(root.left)
rightDepth=1+self.maxDepth(root.right)
return max(leftDepth,rightDepth)