Skip to content

Instantly share code, notes, and snippets.

@ChrisLeNeve
Created October 1, 2020 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisLeNeve/2497c1c877246c94fb45634f251ab43f to your computer and use it in GitHub Desktop.
Save ChrisLeNeve/2497c1c877246c94fb45634f251ab43f to your computer and use it in GitHub Desktop.
class Scratch {
public static void main(String[] args) {
Scratch app = new Scratch();
Node root = app.setup();
app.printBreadthFirst(root);
}
public void printBreadthFirst(Node node) {
int height = getHeight(node);
for (int i = 1; i <= height; i++) {
print(node, i);
}
}
public void print(Node node, int level) {
if (level == 1) {
System.out.println(node.value);
}
if (node.left != null) {
print(node.left, level - 1);
}
if (node.right != null) {
print(node.right, level - 1);
}
}
public int getHeight(Node node) {
if (node.left == null && node.right == null) {
return 1;
}
int heightLeft = (node.left == null ? 0 : getHeight(node.left));
int heightRight = (node.right == null ? 0 : getHeight(node.right));
return (heightLeft > heightRight ? heightLeft + 1: heightRight + 1);
}
public Node setup() {
Node root = new Node(1);
Node two = new Node(2);
Node three = new Node(3);
Node four = new Node(4);
Node five = new Node(5);
Node six = new Node(6);
Node seven = new Node(7);
two.left = four;
two.right = five;
root.left = two;
root.right = three;
five.left = six;
five.right = seven;
return root;
}
}
class Node {
Node left;
Node right;
int value;
public Node(int value) {
this.value = value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment