Minimum and Maximum Leaf Depth in a Tree: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
(Created page with "=Internal= * Trees")
 
Line 1: Line 1:
=Internal=
=Internal=
* [[Trees#Tree_Algorithms|Trees]]
* [[Trees#Tree_Algorithms|Trees]]
=Overview=
Minimum leaf depth:
<syntaxhighlight lang='java'>
public static int minLeafDepth(N n, int depth) {
  if (n == null) {
    return Integer.MAX_VALUE;
  }
  if (n.l == null && n.r == null) {
    // I am a leaf
    return depth;
  }
  return Math.min(minLeafDepth(n.l, depth + 1), minLeafDepth(n.r, depth + 1));
}
</syntaxhighlight>

Revision as of 23:18, 10 November 2021

Internal

Overview

Minimum leaf depth:

public static int minLeafDepth(N n, int depth) {
  if (n == null) {
     return Integer.MAX_VALUE;
  }
  if (n.l == null && n.r == null) {
     // I am a leaf
     return depth;
  }
  return Math.min(minLeafDepth(n.l, depth + 1), minLeafDepth(n.r, depth + 1));
}