Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.epam.rd.autocode.bstprettyprint;
- public class PrintableTreeInstance implements PrintableTree {
- private TreeNode treeNode;
- @Override
- public void add(int value) {
- TreeNode node = treeNode;
- while (true) {
- if (node == null) {
- treeNode = new TreeNode(value);
- break;
- } else {
- if (node.getValue() < value) {
- if (node.getLeft() != null) {
- node = node.getLeft();
- } else {
- node.setLeft(new TreeNode(value));
- break;
- }
- }
- if (node.getValue() > value) {
- if (node.getRight() != null) {
- node = node.getRight();
- } else {
- node.setRight(new TreeNode(value));
- break;
- }
- }
- }
- }
- }
- @Override
- public String prettyPrint() {
- StringBuilder sb = new StringBuilder();
- traverse(treeNode, treeNode, sb, 0);
- return sb.toString();
- }
- private void traverse(TreeNode node, TreeNode temp, StringBuilder sb, int space) {
- if (node != null) {
- traverse(node.getRight(), node, sb, space + log10(node.getValue()) + 1);
- addSpaces(sb, space);
- addPrePattern(sb, temp, node);
- addPostPattern(sb, node);
- traverse(node.getLeft(), node, sb, space + log10(node.getValue()) + 1);
- }
- }
- private int log10(int n) {
- int ans = 0;
- while (n != 0) {
- ans++;
- n /= 10;
- }
- return ans;
- }
- private void addSpaces(StringBuilder sb, int spaces) {
- for (int i = 0; i < spaces - 1; i++) {
- sb.append(' ');
- }
- }
- private void addPostPattern(StringBuilder sb, TreeNode node) {
- if (node.hasLeft() || node.hasRight()) {
- if (!node.hasLeft()) {
- sb.append('┘');
- }
- if (!node.hasRight()) {
- sb.append('┐');
- }
- if (node.hasRight() && node.hasLeft()) {
- sb.append('┤');
- }
- }
- sb.append("\n");
- }
- private void addPrePattern(StringBuilder sb, TreeNode preNode, TreeNode node) {
- if (preNode.getRight() == node) {
- sb.append('┌');
- }
- if (preNode.getLeft() == node) {
- sb.append('└');
- }
- sb.append(node.getValue());
- }
- private static class TreeNode {
- private final Integer value;
- private TreeNode left;
- private TreeNode right;
- public TreeNode(int value) {
- this.value = value;
- }
- public boolean hasLeft() {
- return this.left != null;
- }
- public boolean hasRight() {
- return this.right != null;
- }
- public Integer getValue() {
- return value;
- }
- public TreeNode getLeft() {
- return left;
- }
- public TreeNode getRight() {
- return right;
- }
- public void setLeft(TreeNode left) {
- this.left = left;
- }
- public void setRight(TreeNode right) {
- this.right = right;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement