Binary tree implementation

Run Settings
LanguageJava
Language Version
Run Command
import java.util.concurrent.ThreadLocalRandom; import static java.lang.System.out; final class Main { public static void main(String[] args) { var root = new Node(10); for (int i = 0; i < 10; i++) { root.add(new Node(ThreadLocalRandom.current().nextInt(20))); } out.println(new BinaryTree(root).size()); } }
import static java.util.Objects.requireNonNull; final class Node { private Node left; private Node right; private final int value; public Node(int value) { this.value = value; } public int value() { return value; } public Node left() { return left; } public Node right() { return right; } public Node add(Node node) { requireNonNull(node); if (node.value < value) { if (left == null) { left = node; } else { left.add(node); } } else { if (right == null) { right = node; } else { right.add(node); } } return this; } @Override public String toString() { return String.format("[%s, %s, %s]", left == null ? null : left.value, value, right == null ? null : right.value); } }
final class BinaryTree { private final Node root; public BinaryTree(Node root) { this.root = root; } public BinaryTree() { this(null); } public int size() { return calculateSize(root); } private int calculateSize(Node root) { return root == null ? 0 : 1 + calculateSize(root.left()) + calculateSize(root.right()); } @Override public String toString() { return String.format("[%s]", toString(root)); } private String toString(Node root) { StringBuilder stringBuilder = new StringBuilder(); if (root == null) { return "null"; } stringBuilder.append(root.value()); stringBuilder.append("\nleft:\t"); stringBuilder.append(toString(root.left())); stringBuilder.append("\nright:\t"); stringBuilder.append(toString(root.right())); return stringBuilder.toString(); } }
Editor Settings
Theme
Key bindings
Full width
Lines