File : Tree.java
----------------------------------------------------------------------------
package org.developersbrain.solutions;
class BinaryNode{
BinaryNode left;
BinaryNode right;
Integer t;
BinaryNode(Integer t){
this.t = t;
left = null;
right = null;
}
}
public class Tree {
BinaryNode root;
Tree(){
root = null;
}
void add(Integer t){
BinaryNode bn=new BinaryNode(t);
if(root==null){
root = bn;
}else{
BinaryNode node=root;
BinaryNode tmp=null;
while(node!=null){
tmp = node;
if(node.t <= bn.t){
node=node.right;
}else{
node=node.left;
}
}
if(tmp.t<=bn.t){
tmp.right=bn;
}else{
tmp.left=bn;
}
}
}
void traverse(){
BinaryNode parent=root;
BinaryNode child=root.left;
while(child!=null){
if(parent!=null){
parent.left=child.right;
child.right=parent;
}
if(child.left!=null){
parent = child;
child=child.left;
}else{
if(child==root){
System.out.println(child.t+" ==> Root element");
}else{
System.out.println(child.t);
}
child=child.right;
parent=null;
}
}
}
}
----------------------------------------------------------------------------
package org.developersbrain.solutions;
class BinaryNode{
BinaryNode left;
BinaryNode right;
Integer t;
BinaryNode(Integer t){
this.t = t;
left = null;
right = null;
}
}
public class Tree {
BinaryNode root;
Tree(){
root = null;
}
void add(Integer t){
BinaryNode bn=new BinaryNode(t);
if(root==null){
root = bn;
}else{
BinaryNode node=root;
BinaryNode tmp=null;
while(node!=null){
tmp = node;
if(node.t <= bn.t){
node=node.right;
}else{
node=node.left;
}
}
if(tmp.t<=bn.t){
tmp.right=bn;
}else{
tmp.left=bn;
}
}
}
void traverse(){
BinaryNode parent=root;
BinaryNode child=root.left;
while(child!=null){
if(parent!=null){
parent.left=child.right;
child.right=parent;
}
if(child.left!=null){
parent = child;
child=child.left;
}else{
if(child==root){
System.out.println(child.t+" ==> Root element");
}else{
System.out.println(child.t);
}
child=child.right;
parent=null;
}
}
}
}
File:MainClass.java
----------------------------------------------------------------------------
package org.developersbrain.solutions;
import java.io.IOException;
public class MainClass {
public static void main(String[] args) throws IOException{
Tree tr=new Tree();
tr.add(10);
tr.add(20);
tr.add(5);
tr.add(7);
tr.add(8);
tr.add(6);
tr.add(4);
tr.add(25);
tr.add(24);
tr.add(30);
tr.add(19);
tr.add(17);
tr.add(16);
tr.add(18);
System.out.println("Tree Implementation - Traverse");
System.out.println("---------------------------");
System.out.println();
tr.traverse();
}
}
Output:
-----------------------------------------------------------
Tree Implementation - Traverse
---------------------------
4
5
6
7
8
10 ==> Root element
16
17
18
19
20
24
25
30
Comments
Post a Comment