Skip to content

Instantly share code, notes, and snippets.

@slofurno
Created April 11, 2017 16:15
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 slofurno/5ec1f860616c42945bd95c9443a90075 to your computer and use it in GitHub Desktop.
Save slofurno/5ec1f860616c42945bd95c9443a90075 to your computer and use it in GitHub Desktop.
import java.util.LinkedList;
import java.util.Queue;
import java.util.function.Consumer;
public class BinaryTreeFlip {
public static void main(String[] args) throws Exception {
BinaryTree binaryTree = BinaryTree.buildTestTree(4, 2, 7, 1, 3, 6, 9);
//BinaryTree bt2 = BinaryTree.buildTestTree(4, 2, 7, 1, 3, 6, 9);
//BinaryTree bt2 = BinaryTree.buildTestTree(4, 2, 7, 1, 3, 6, 9, 10);
BinaryTree bt2 = BinaryTree.buildTestTree(4, 2, 8, 1, 3, 6, 9);
System.out.println("binaryTree.equals(bt2) = " + binaryTree.equals(bt2));
System.out.println("binaryTree.equals(binaryTree) = " + binaryTree.equals(binaryTree));
binaryTree.levelOrderTraversal(BinaryTree::printNode);
System.out.println();
binaryTree.levelOrderTraversal(BinaryTree::swapChildren);
binaryTree.levelOrderTraversal(BinaryTree::printNode);
}
private static class BinaryTree {
Node head;
BinaryTree(Node head) {
this.head = head;
}
static class Node {
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
}
}
// takes an array representing the tree values i.e. level order traversal
static BinaryTree buildTestTree(int... values) {
Queue<Node> q = new LinkedList<>();
Node n = new Node(values[0]);
BinaryTree binaryTree = new BinaryTree(n);
q.offer(n);
for (int i = 1; i < values.length; i++) {
Node curr = q.poll();
curr.left = new Node(values[i++]);
q.offer(curr.left);
if (i < values.length) {
curr.right = new Node(values[i]);
q.offer(curr.right);
}
}
return binaryTree;
}
void levelOrderTraversal(Consumer<Node> nodeConsumer) {
Queue<Node> q = new LinkedList<>();
q.offer(head);
while (!q.isEmpty()) {
Node curr = q.poll();
if (curr.left != null) q.offer(curr.left);
if (curr.right != null) q.offer(curr.right);
nodeConsumer.accept(curr);
}
}
static void printNode(Node node) {
System.out.print(node.data + " ");
}
static void swapChildren(Node node) {
Node tmp = node.left;
node.left = node.right;
node.right = tmp;
}
private boolean equals_(Node a, Node b) {
if (a == null && b == null) {
return true;
}
if (a == null || b == null) {
return false;
}
return a.data == b.data && equals_(a.left, b.left) && equals_(a.right, b.right);
}
public boolean equals(Object o) {
if (o == null || !(o instanceof BinaryTree)) return false;
BinaryTree that = (BinaryTree)o;
return equals_(this.head, that.head);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment