Last active
July 18, 2018 07:18
-
-
Save akhr/e782651ae0888ef6a49f0d1bc9eabf0a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Arra2Tree { | |
public class Node { | |
int data; | |
Node left; | |
Node right; | |
public Node(int data) { | |
this.data = data; | |
} | |
public void setData(int data) { | |
this.data = data; | |
} | |
public int getData() { | |
return this.data; | |
} | |
public Node getLeft() { | |
return left; | |
} | |
public void setLeft(Node left) { | |
this.left = left; | |
} | |
public Node getRight() { | |
return right; | |
} | |
public void setRight(Node right) { | |
this.right = right; | |
} | |
} | |
public static void main(String[] args) { | |
// int[] input = new int[]{5,9,2,3,5,0,7,6,8,1}; // -2,0,1,2,3,5,6,7,8,9 | |
int[] input = new int[]{1,2,3,4,5,6}; // -2,0,1,2,3,5,6,7,8,9 | |
Arrays.sort(input); | |
Arra2Tree obj = new Arra2Tree(); | |
Node x = obj.createTree(input, 0, input.length-1); | |
System.out.println(" Root "+x.data); | |
obj.inOrder(x); | |
} | |
public Node createTree(int[] input, int start, int end) { | |
if(start > end) | |
return null; | |
int mid = (start+end)/2; | |
Node child = new Node(input[mid]); | |
child.left = createTree(input,start,mid-1); | |
child.right = createTree(input,mid+1,end); | |
return child; | |
} | |
public void inOrder(Node root) { | |
if( root == null) | |
return; | |
inOrder(root.left); | |
System.out.println(root.data); | |
inOrder(root.right); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment