2017-02-03

Tree with One child - Implementation in Java

class Node {
String name;
Node child;
}


public class TreeTest {
static Node add(Node x, String child) {
if (x == null) {
Node node = new Node();
node.name = child;
x=node;
return x;
}
if (x.child != null) {
add(x.child, child);
}
else{
Node node = new Node();
node.name = child;
x.child=node;
}
return x;
}



public static void main(String[] args) {
Node node =null;
Node t=TreeTest.add(node, "1");
    t=TreeTest.add(t, "2");
    t=TreeTest.add(t, "3");
    t=TreeTest.add(t, "4");
    t=TreeTest.add(t, "5");


while(t!=null){
System.out.println(t.name);
t=t.child;
}

}
}

No comments:

Post a Comment