Minimum and Maximum Leaf Depth in a Tree: Difference between revisions
Jump to navigation
Jump to search
(One intermediate revision by the same user not shown) | |||
Line 2: | Line 2: | ||
* [[Trees#Tree_Algorithms|Trees]] | * [[Trees#Tree_Algorithms|Trees]] | ||
=Overview= | =Overview= | ||
Context: [[Tree_Representation_in_Memory|Tree Representation in Memory]] | |||
<syntaxhighlight lang='java'> | <syntaxhighlight lang='java'> | ||
public static int minLeafDepth(N n, int depth) { | public static int minLeafDepth(N n, int depth) { | ||
Line 13: | Line 14: | ||
} | } | ||
return Math.min(minLeafDepth(n.l, depth + 1), minLeafDepth(n.r, depth + 1)); | return Math.min(minLeafDepth(n.l, depth + 1), minLeafDepth(n.r, depth + 1)); | ||
} | |||
</syntaxhighlight> | |||
<syntaxhighlight lang='java'> | |||
public static int maxLeafDepth(N n, int depth) { | |||
if (n == null) { | |||
return Integer.MIN_VALUE; | |||
} | |||
if (n.l == null && n.r == null) { | |||
// I am a leaf | |||
return depth; | |||
} | |||
return Math.max(maxLeafDepth(n.l, depth + 1), maxLeafDepth(n.r, depth + 1)); | |||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 23:32, 10 November 2021
Internal
Overview
Context: Tree Representation in Memory
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));
}
public static int maxLeafDepth(N n, int depth) {
if (n == null) {
return Integer.MIN_VALUE;
}
if (n.l == null && n.r == null) {
// I am a leaf
return depth;
}
return Math.max(maxLeafDepth(n.l, depth + 1), maxLeafDepth(n.r, depth + 1));
}