-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
14 changed files
with
329 additions
and
146 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
package org.behrang.algorithm.tree; | ||
|
||
import java.util.function.Consumer; | ||
|
||
public final class Functions { | ||
private Functions() { | ||
throw new RuntimeException(); | ||
} | ||
|
||
public static Node<?> leftmostDescendantAtDepth(Node<?> node, int depth) { | ||
return leftmostDescendantAtDepth(node, 0, depth); | ||
} | ||
|
||
private static Node<?> leftmostDescendantAtDepth(Node<?> node, int level, int depth) { | ||
if (level >= depth) { | ||
return node; | ||
} else if (node.isLeaf()) { | ||
return null; | ||
} else { | ||
var leftChild = node.getLeftChild(); | ||
var leftmost = leftmostDescendantAtDepth(leftChild, level + 1, depth); | ||
while (leftmost == null && leftChild.hasRightSibling()) { | ||
leftChild = leftChild.getRightSibling(); | ||
leftmost = leftmostDescendantAtDepth(leftChild, level + 1, depth); | ||
} | ||
|
||
return leftmost; | ||
} | ||
} | ||
|
||
public static <T> void prePostOrder(Node<T> node, Consumer<Node<T>> preConsumer, Consumer<Node<T>> postConsumer) { | ||
preConsumer.accept(node); | ||
|
||
node.getChildren().forEach(n -> { | ||
prePostOrder(n, preConsumer, postConsumer); | ||
}); | ||
|
||
postConsumer.accept(node); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.