Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* package whatever; // don't place package name! */
- import java.util.*;
- import java.lang.*;
- import java.io.*;
- /* Name of the class has to be "Main" only if the class is public. */
- class Ideone
- {
- static class Node {
- Node left;
- Node right;
- int value;
- boolean set;
- public Node(int value) {
- this.value = value;
- set = true;
- }
- public Node(boolean set) {
- set = set;
- }
- }
- public static Node convertToTree(int[] arr) {
- if (arr.length == 0) { return null; }
- return cttHelper(arr, 0, arr.length-1);
- }
- public static Node cttHelper(int[] arr, int i, int j) {
- if (i==j) {
- return new Node(arr[i]);
- } else {
- int mid = (i+j) / 2;
- Node root = new Node(arr[mid]);
- root.right = cttHelper(arr, mid+1, j);
- if (mid-1 >= i) {
- root.left = cttHelper(arr, i, mid-1);
- }
- return root;
- }
- }
- public static void printTree(Node n) {
- if (n == null) { System.out.println("null"); return; }
- Queue<Node> q1 = new LinkedList<Node>();
- Queue<Node> q2 = new LinkedList<Node>();
- int d = getMaxDepth(n);
- int spacing = (int) Math.pow(2, d-1) * 4;
- q1.add(n);
- while (!q1.isEmpty()) {
- // Because we're adding dummy nodes, need to know when to quit
- if (d-- < 1) {
- break;
- }
- for (Node node : q1) {
- if (node.left != null) {
- q2.add(node.left);
- } else {
- q2.add(new Node(false));
- }
- if (node.right != null) {
- q2.add(node.right);
- } else {
- q2.add(new Node(false));
- }
- }
- if (q1.peek().set) {
- System.out.printf("%"+spacing/2+"d", q1.remove().value);
- } else {
- insertSpaces(spacing/2);
- q1.remove();
- }
- while(!q1.isEmpty()) {
- if (q1.peek().set) {
- System.out.printf("%"+spacing+"d", q1.remove().value);
- } else {
- insertSpaces(spacing);
- q1.remove();
- }
- }
- while(!q2.isEmpty()) {
- q1.add(q2.remove());
- }
- spacing/=2;
- System.out.println();
- }
- }
- public static void insertSpaces(int d) {
- for (int i = 0; i < d; ++i) {
- System.out.print(" ");
- }
- }
- public static int getMaxDepth(Node n) {
- if (n == null) {
- return -1;
- }
- return getMaxDepthHelper(n, 0);
- }
- public static int getMaxDepthHelper(Node n, int d) {
- if (n == null) {
- return d;
- } else {
- int leftMaxDepth = getMaxDepthHelper(n.left, d+1);
- int rightMaxDepth = getMaxDepthHelper(n.right, d+1);
- return Math.max(leftMaxDepth, rightMaxDepth);
- }
- }
- public static void main (String[] args) throws java.lang.Exception
- {
- // your code goes here
- int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
- Node root = convertToTree(arr);
- printTree(root);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement