【发布时间】:2014-07-22 22:28:17
【问题描述】:
我正在将职业杯指南作为速成课程,通过基本的 CS 原则,并坚持计算二叉树的最小/最大深度的示例。由于这是我在几乎每个示例中遇到的相同问题,因此我认为我会在这里发布一个问题。
这些指令是实现一个检查树是否平衡的方法。为了做到这一点,您需要比较最小深度和最大深度,并确保它们的差不大于 1。这个原理非常简单。第 15 行的方法就是为了做到这一点。
但是,我不明白每个辅助方法(maxDepth 和 minDepth)的返回语句中发生了什么。如何从root.left 或root.right 派生一个数字?
Math.max 函数是否只是假设 1 或 0 是否存在 value/null 节点,或者,由于没有指定值(只是 Node 对象),Math.max(maxDepth(root.left), maxDepth(root.right) 本身是否等于 @ 987654330@,从而将返回值增加1,直到两个节点都为空?
如果是这样,这是用于计算树的最小/最大深度的一般过程:
minDepth = 根有孩子吗? yes = minDepth = 1,no = minDepth = 0(如果有根)
maxDepth = 循环遍历两个分支,直到找到离根最远的叶子。保持一个计数器来确定叶子。
1 public static int maxDepth(TreeNode root) {
2 if (root == null) {
3 return 0;
4 }
5 return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
6 }
7
8 public static int minDepth(TreeNode root) {
9 if (root == null) {
10 return 0;
11 }
12 return 1 + Math.min(minDepth(root.left), minDepth(root.right));
13 }
14
15 public static boolean isBalanced(TreeNode root){
16 return (maxDepth(root) - minDepth(root) <= 1);
17 }
【问题讨论】:
标签: java c++ binary-tree binary-search-tree