您的位置:首页 > 其它

leetcode maximum-depth-of-binary-tree

2017-05-17 15:42 309 查看
题目:

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.

今天开始总结之前做过的leetcode的题目,先来道最简单的。求二叉树的最大深度

思路:通过递归的方法,二叉树无非左右两边,那么最大深度即为:  Max(左子树的最大深度,右子树的最大深度) + 1(这里1表示root节点高度为1)

public class Solution {
public int maxDepth(TreeNode root) {
if(root == null)//若根节点为空,则返回0
return 0;
else {
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
}


ps:代码不一定最优,若有问题,欢迎纠错。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: