carry the code from core-java to data-structures module
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.printbinarytree;
|
||||
|
||||
public class BinaryTreeModel {
|
||||
|
||||
private Object value;
|
||||
private BinaryTreeModel left;
|
||||
private BinaryTreeModel right;
|
||||
|
||||
public BinaryTreeModel(Object value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public Object getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(Object value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public BinaryTreeModel getLeft() {
|
||||
return left;
|
||||
}
|
||||
|
||||
public void setLeft(BinaryTreeModel left) {
|
||||
this.left = left;
|
||||
}
|
||||
|
||||
public BinaryTreeModel getRight() {
|
||||
return right;
|
||||
}
|
||||
|
||||
public void setRight(BinaryTreeModel right) {
|
||||
this.right = right;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.printbinarytree;
|
||||
|
||||
import java.io.PrintStream;
|
||||
|
||||
public class BinaryTreePrinter {
|
||||
|
||||
private BinaryTreeModel tree;
|
||||
|
||||
public BinaryTreePrinter(BinaryTreeModel tree) {
|
||||
this.tree = tree;
|
||||
}
|
||||
|
||||
private String traversePreOrder(BinaryTreeModel root) {
|
||||
|
||||
if (root == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(root.getValue());
|
||||
|
||||
String pointerRight = "└──";
|
||||
String pointerLeft = (root.getRight() != null) ? "├──" : "└──";
|
||||
|
||||
traverseNodes(sb, "", pointerLeft, root.getLeft(), root.getRight() != null);
|
||||
traverseNodes(sb, "", pointerRight, root.getRight(), false);
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void traverseNodes(StringBuilder sb, String padding, String pointer, BinaryTreeModel node,
|
||||
boolean hasRightSibling) {
|
||||
|
||||
if (node != null) {
|
||||
|
||||
sb.append("\n");
|
||||
sb.append(padding);
|
||||
sb.append(pointer);
|
||||
sb.append(node.getValue());
|
||||
|
||||
StringBuilder paddingBuilder = new StringBuilder(padding);
|
||||
if (hasRightSibling) {
|
||||
paddingBuilder.append("│ ");
|
||||
} else {
|
||||
paddingBuilder.append(" ");
|
||||
}
|
||||
|
||||
String paddingForBoth = paddingBuilder.toString();
|
||||
String pointerRight = "└──";
|
||||
String pointerLeft = (node.getRight() != null) ? "├──" : "└──";
|
||||
|
||||
traverseNodes(sb, paddingForBoth, pointerLeft, node.getLeft(), node.getRight() != null);
|
||||
traverseNodes(sb, paddingForBoth, pointerRight, node.getRight(), false);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void print(PrintStream os) {
|
||||
os.print(traversePreOrder(tree));
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user