题目链接:Maximum Depth of Binary Tree
题意很简单,计算给定二叉树的深度。
那么二叉树的深度就可以通过左右子树来计算,显然,其为1+左右子树中大的深度值。
那么通过使用递归可以很简单的实现。
代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
int maxdepth = 0;
if(root==null)
return 0;
int maxl = maxDepth(root.left);
int maxr = maxDepth(root.right);
maxdepth = 1 + ((maxl>maxr)? maxl:maxr);
return maxdepth;
}
}