题目:
ps:代码不一定最优,若有问题,欢迎纠错。。。
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:代码不一定最优,若有问题,欢迎纠错。。。