LeetCode Example:
二叉树:[3,9,20,null,null,15,7],
![5da3a246957b98f8dd816eb091756da0.png](https://i-blog.csdnimg.cn/blog_migrate/653e77c5ee30da58e79692411729b3b9.png)
return its depth = 3.
大概思路如下:
1、首先判断根节点是否为空,如果为空,则返回0;2、如果根节点不为空,再去判断左右子节点是否为空,进行递归调用;3、最后返回leftMax、rightMax的最大值加1等于二叉树的最大深度;Java代码实现如下:
package leetcode;
/**
* 计算二叉树的最大深度
*/
public class MaximumDepthBinaryTree {
public static int maxDepth(TreeNode root) {
int depth = 0;
if (root != null) {
int leftMax = maxDepth(root.left);int rightMax = maxDepth(root.right);
depth = 1 + Math.max(leftMax, rightMax);
}
return depth;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
TreeNode t1 = new TreeNode(9);
TreeNode t2 = new TreeNode(20);
TreeNode t3 = new TreeNode(15);
TreeNode t4 = new TreeNode(7);
t2.left = t3;
t2.right = t4;
root.left = t1;
root.right = t2;
System.out.println(maxDepth(root));
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
往期内容:
给定一颗二叉树,找到它的最小深度。
Spring中@Controller 、@Repository 、@Service 、@Component 注解的作用详解
Java语法:详解retry标签的基本用法
JAVA并发编程:线程池ThreadPoolExecutor源码分析
JAVA并发编程:阻塞队列BlockingQueue之SynchronousQueue
JAVA并发编程:详解Executors工厂创建线程池的5种方法
JAVA并发编程:详解线程池ThreadPoolExecutor的基本应用
JAVA并发编程:详解线程池的工作原理
更多精彩内容请关注“菜鸟技术栈”微信公众号,一起交流学习,让学习成为一种享受!!!