Adjacency Linked List Cycle Detection - Java - java

I have some problem checking if my adjacency list has a cycle or not.
I want to make a function that checks if my adjacency list has existing at least one cycle.
Based on my program. First, I have to input the Root Node, followed by a number of nodes, the nodes in the graph, number of edges, and the adjacency list representing the edges. Each entry in the adjacency list contains a pair of nodes.
Sample input:
Root node: "A"
Number of nodes: 3
Vertices/Nodes:
A
B
C
Number of edges: 3
A
B
B
C
C
A
A --> B
B --> C
C --> A
The sample input above has a cycle: [ A --> B --> C --> A ] I want to output whether it has a cycle or not.
This is my program so far:
import java.util.Scanner;
class Neighbor {
public int vertexNum;
public Neighbor next;
public Neighbor(int vnum, Neighbor nbr) {
this.vertexNum = vnum;
next = nbr;
}
}
class Vertex {
String name;
Neighbor adjList;
Vertex(String name, Neighbor neighbors) {
this.name = name;
this.adjList = neighbors;
}
}
public class DirectedCycle {
Vertex[] adjLists;
public DirectedCycle() {
Scanner sc = new Scanner(System.in);
//Root Node
System.out.print("Root node: ");
String rn = sc.nextLine();
//Number of nodes
System.out.print("Number of vertices/nodes: ");
int nodes = sc.nextInt();
adjLists = new Vertex[nodes];
//List of nodes
System.out.println("Vertices:");
for (int v=0; v < adjLists.length; v++) {
String letter = sc.next();
adjLists[v] = new Vertex(letter, null);
}
//Number of edges
System.out.print("Number of edges: ");
int edges = sc.nextInt();
System.out.println("<v1> <v2>");
for(int i=0; i<edges; i++) {
int v1 = indexForName(sc.next());
int v2 = indexForName(sc.next());
adjLists[v1].adjList = new Neighbor(v2, adjLists[v1].adjList);
}
}
int indexForName(String name) {
for (int v=0; v < adjLists.length; v++) {
if (adjLists[v].name.equals(name)) {
return v;
}
}
return -1;
}
public void print() {
System.out.println();
for (int v=0; v < adjLists.length; v++) {
System.out.print(adjLists[v].name);
for (Neighbor nbr=adjLists[v].adjList; nbr != null; nbr=nbr.next) {
String name = adjLists[nbr.vertexNum].name;
System.out.print(" --> " + name);
}
System.out.println("\n");
}
}
public static void main(String[] args) {
DirectedCycle graph = new DirectedCycle();
graph.print();
}
}
My program above doesn't have yet a function that checks cycle and also I want to implement the root node thing.. If anyone can improve my program above just answer me and give me some code I can rely. Thanks! (I'm beginner!)

The most efficient way to detect a cycle in Floyd's Cycle detection algo., which is basically moving two pointers over the linked list, one moving at normal one step at a time slow pointer and the other with double the speed of the slow pointer, i.e fast pointer.
Java code for the same.
boolean detectloop(Node list) {
if(list == null)
return false;
Node slow, fast;
slow = fast = list;
while(true) {
slow = slow.next;
if(fast.next != null)
fast = fast.next.next;
else
return false;
if(slow == null || fast == null)
return false;
if(slow == fast)
return true;
}
}

To check a cycle of a linked list, you want to iterate though with two different pointers, one moving through the list twice as fast. If there is a cycle, it will eventually be detected using this method. Also, for the end condition, you can check to see if all nodes have been visited, and if so, there is no cycle.

Related

Deleting N nodes after M nodes in a Singly Linked List

Given a linked list, delete N nodes after skipping M nodes of a linked list until the last of the linked list
This is the Java program I wrote to solve this problem. For certain large test cases it's showing error,
"Exception in thread "main" java.lang.NullPointerException: Cannot assign field "next" because "" is null
at SinglyLinkedList.deleteNNodesAfterEveryMNodes(DeleteNNodesAfterMNodesOfALinkedList.java:88)
at DeleteNNodesAfterMNodesOfALinkedList.main(DeleteNNodesAfterMNodesOfALinkedList.java:127)"
import java.io.*;
import java.util.*;
class Link
{
public int data;
public Link next;
public Link(int d)
{
data = d;
}
public void displayLink()
{
System.out.print(data + " ");
}
}
class SinglyLinkedList
{
public Link first;
public SinglyLinkedList()
{
first = null;
}
public boolean isEmpty()
{
return(first == null);
}
public void insertLast(int d)
{
Link nl = new Link(d);
if(isEmpty())
{
first = nl;
}
else
{
Link curr = first;
while(curr.next != null)
{
curr = curr.next;
}
curr.next = nl;
}
}
public void displayList()
{
Link curr = first;
while(curr != null)
{
curr.displayLink();
curr = curr.next;
}
}
public void deleteNNodesAfterEveryMNodes(int N, int M)
{
Link curr1=first, curr2=first;
int n=N+M, m=M;
while(curr1!=null && curr1.next!=null)
{
while(curr2!=null && n!=0)
{
if(m != 1)
{
curr1 = curr1.next;
m--;
}
curr2 = curr2.next;
n--;
}
curr1.next = curr2;
m = M;
n = N+M;
curr1 = curr2;
}
}
}
class DeleteNNodesAfterMNodesOfALinkedList
{
public static void main(String st[])
{
Scanner sc = new Scanner(System.in);
SinglyLinkedList sll = new SinglyLinkedList();
int count, d, N, M;
System.out.println("Enter the number of integers you want to store in the singly linked list: ");
count = sc.nextInt();
System.out.println("\nEnter the " + count + " integers: ");
for(int i=0; i<count; i++)
{
d = sc.nextInt();
sll.insertLast(d);
}
System.out.println("\nThe singly linked list is: ");
sll.displayList();
System.out.println("\n\nEnter the value of 'M', the number of nodes to be skipped: ");
M = sc.nextInt();
System.out.println("\nEnter the value of 'N', the number of nodes now to be deleted: ");
N = sc.nextInt();
sll.deleteNNodesAfterEveryMNodes(N, M);
System.out.println("\nThe resultant singly linked list is: ");
sll.displayList();
}
}
I can't figure out what went wrong and how is assigning curr1.next = curr2; is of any issue at line 127
You can either try to put an additional check of curr1!=null in the second while loop or simplify the problem.
Simplifying the problem can be done by:
Using a for loop (m number of times) to traverse the list.
Using another for loop (n number of times) to call a piece of code that deletes the nodes one by one.
Also check for edge conditions i.e. if m + n < size and so on.

Depth First Search on graph using Iterator

I'm trying to make this into a Depth First Search. At first it was in Breadth First and now I'm trying to convert it. I've been working on this for DAYS and have tried multiple different things.
import java.util.*;
class Graph{
class Edge{
int v,w;
public Edge(int v,int w){
this.v=v; this.w=w;
}
#Override
public String toString(){
return "("+v+","+w+")";
}
}
List<Edge> G[];
public Graph(int n){
G=new LinkedList[n];
for(int i=0;i<G.length;i++)
G[i]=new LinkedList<Edge>();
}
boolean isConnected(int u,int v){
for(Edge i: G[u])
if(i.v==v) return true;
return false;
}
void addEdge(int u,int v,int w)
{
G[u].add(0,new Edge(v,w));
G[v].add(0,new Edge(u,w));
}
public int getWeight(int u, int v)
{
for (Edge e : G[u])
{
if (e.v == v)
{
return e.w ;
}
}throw new NoSuchElementException();
}
#Override
public String toString(){
String result="";
for(int i=0;i<G.length;i++)
result+=i+"=>"+G[i]+"\n";
return result;
}
// here's the problem though
void DFS(int s)
{
boolean visited[] = new boolean[G.length];
LinkedList<Integer> stack = new LinkedList<Integer>();
stack.push(s);
while (stack.size() != 0)
{
s = stack.pop();
System.out.print(s+" ");
Iterator<Edge> i = G[s].listIterator();
if (!visited[s])
{
visited[s] = true;
while (i.hasNext())
{
int n = i.next().v;
stack.push(n);
}
}
}
}
}
public class GraphEx
{
public static void main(String[] args)
{
Graph g=new Graph(10);
g.addEdge(1,2,38);
g.addEdge(1,5 ,19);
g.addEdge(1,3 ,35);
g.addEdge(1,4 ,11);
g.addEdge(4,3,27);
g.addEdge(3,6,13);
g.addEdge(3,5,28);
g.addEdge(5,6,26);
System.out.println(g);
System.out.println("\nDFS");
g.DFS(1);
This prints out:
DFS
1 2 1 5 1 3 1 4 1 3 6 3 5 5 6 3 4
That would be perfect if the first part didn't have the ones inserted for all the print numbers after 2 and then ended after 6. This is the closest output to what I think I should be getting I've gotten out of all the code I've written so I posted this.
EDIT: Here's the original that I'm trying to reconvert
void BFS(int s)
{
// Mark all the vertices as not visited(By default
// set as false)
boolean visited[] = new boolean[G.length];
// Create a queue for BFS
LinkedList<Integer> queue = new LinkedList<Integer>();
// Mark the current node as visited and enqueue it
visited[s]=true;
queue.add(s);
while (queue.size() != 0)
{
// Dequeue a vertex from queue and print it
s = queue.poll();
System.out.print(s+" ");
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it
// visited and enqueue it
Iterator<Edge> i = G[s].listIterator();
while (i.hasNext())
{
int n = i.next().v;
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
DFS is an algorithm that is usually run on trees which do not have cycles or links back to their parents. This causes two pretty simple problems for your graph implementation. Problem 1 is that each vertex you have points back to it's "parent". For example, vertex 1 has an edge to vertex 2, and vertex 2 has an edge to vertex 1. When edge 2 is visited, all of it's children are put onto the stack. When this happens, you are putting vertex 1, which has been visited already, back onto the stack. Issue 2 is that sometimes you have vertices pushed onto the stack multiple times before they're visited. For example, vertices 5 and 3 both add 6 to the stack before 6 is visited. One way to quickly fix both of these problems is to do this:
while (stack.size() != 0)
{
s = stack.pop();
if(visited[s]) //add these two lines
continue;
System.out.print(s+" ");
Iterator<Edge> i = G[s].listIterator();
if (!visited[s])
{
visited[s] = true;
while (i.hasNext())
{
int n = i.next().v;
stack.push(n);
}
}
}
If you check the element popped off of the stack to see if it has been visited, you will remove both vertices which are parents that have already been visited, and nodes that have been pushed onto the stack multiple times by their parents. Simply check to see if a vertex has been visited, and if it has just continue with the next iteration of the loop.

Java recursion in implementing an algorithm

I am trying to implement a search algorithm which uses recursion method.
The algorithm should expand startnode to its neighbouring nodes and then select the neighbouring node with least cost and then add that cost to the pathcost(which is initially 0) and the selected least cost node will become the startnode and the search continues again recursively until goalnodeis found.
Below is my code for implementing this recursion. It isn't giving me any errors but it is not giving me the expected solution.
INSTEAD it is adding the cost of each and every neighbouring node (I only need it to add the leastcost node). I have been trying to do it, but can't seem to find any clue how to do it.
Queue<String> frontierNodes = new PriorityQueue<String>();
Queue<Node1> frontierCosts = new PriorityQueue<Node1>(); // here Node1 is class storing the start, end and cost of the map.
public void Search(Node1[] nodes, String startnode, String goalnode, int size, double pathcost){
for(int i=0; i<size;i++) {
if(startnode.equalsIgnoreCase(nodes[i].getStartNode())) {
frontierNodes.add(nodes[i].getEndNode());
frontierCosts.add(new Node1(nodes[i].getCost()));
System.out.println("Frontier Nodes are " +frontierNodes);
System.out.println("Path cost till now "+pathcost);
// Something should be implemented here to add only the least cost
pathcost += frontierCosts.peek().toCostString();
System.out.println("Path cost till now "+pathcost);
}
}
System.out.println("Expanding node... " +frontierNodes.peek());
//Recursive call
Search(nodes, frontierNodes.poll(), goalnode, nodes.length-(frontierNodes.size()), pathcost);
}
I'm not sure why you want to use the PriorityQueue. You should be keeping everything within the scope of the recursive method. For tree traversal recursively, you want to follow the general pattern (psuedo code)
int sumOfLeastCost(Node node){
if(node == null){ return 0; }
int sum = 0;
Node min = null;
for each child{
if(min == null){
min = currentChild;
}else if(currentChild.getCost() < min.getCost()){
min = currentChild;
sum = min.getCost();
}
}
return sum + sumOfLeastCost(min);
}
This will only follow the branches of minimal cost nodes.
Is this closer to what you need?
public double Search(ArrayList<Node1> nodes, String startnode, String goalnode, double pathcost){
//Probably needs a better data structure to hold these
ArrayList<String> neighbours = new ArrayList<>();
ArrayList<Double> neighbourPathCosts = new ArrayList<>();
int i;
for(i=0; i<nodes.size();i++) {
if(startnode.equalsIgnoreCase(nodes.get(i).getStartNode())) {
neighbours.add(nodes.get(i).getEndNode());
neighbourPathCosts.add(nodes.get(i).getCost());
}
}
int indexOfCheapest = -1;
double cheapest = Double.MAX_VALUE;
for(int j = 0; j < neighbours.size(); j++){
if(cheapest > neighbourPathCosts.get(i)){
cheapest = neighbourPathCosts.get(i);
indexOfCheapest = i;
}
}
pathcost += neighbourPathCosts.get(indexOfCheapest);
System.out.println("Path cost till now " + pathcost);
String nextNode = neighbours.get(indexOfCheapest);
System.out.println("Expanding node... " + nextNode );
if(startNode.equals(goalNode)){
return pathcost;
}else{
nodes.remove(i);
//Recursive call
return Search(nodes, nextNode, goalnode, pathcost);
}
}

Breadth First Search: How many states of a vertex are needed?

I am working on Breadth First Search and I tried to write BFS to print all the edges. The first version is adapted from Algorithm book in which a vertex has 3 states: NOT_VISIT (initial state), VISIT and PROCESSED. A vertex is 'VISIT' when you first see it. A vertex is 'PROCESSED' when all of its neighbors are visited. The second version is the one that I wrote, use only 2 states: Initial state and VISITED. Both work:
public static void BFS(Graph g, int start) {
boolean[] visit = new boolean[g.size()];
boolean[] process = new boolean[g.size()];
List<Integer> queue = new ArrayList<Integer>();
queue.add(start);
visit[start] = true;
while (!queue.isEmpty()) {
int currentVertex = queue.remove(0);
process[currentVertex] = true;
List<Integer> adj = g.getAdjacents(currentVertex);
if (adj != null) {
for (Integer i : adj) {
if (visit[i] == false) {
visit[i] = true;
queue.add(i);
}
if (process[i] == false) {
System.out.println(currentVertex + " --- "
+ i);
}
}
}
}
}
public static int BFS2(Graph g, int start) {
List<Integer> queue = new ArrayList<Integer>();
boolean[] visited = new boolean[g.size()];
queue.add(start);
while (!queue.isEmpty()) {
int v = queue.remove(0);
visited[v] = true;// only mark visited[v] = true when processing all
// its neighbors
List<Integer> adj = g.getAdjacents(v);
if (adj != null) {
for (Integer i : adj) {
if (!visited[i]) {
queue.add(i);
System.out.println(v + " --- "
+ i);
}
}
}
}
}
My question is: When is it necessary to have 3 states for a vertex in BFS ? Can you give an example when we need 3 states ?
Usually you add the middle state ("Visit" in your case, commonly "Gray" when using colors to mark nodes) just to visualise how BFS is working. In standard implementation it is not necessary (you may switch to "Visited" without going through the middle state.)
You can see it yourself, try to follow BFS (even with paper and pencil you can do it). You will see that nodes in state "Visit" are equally distanced from source (with maximum difference of 1, to be specific). For educational purposes it is good to do the same with DFS then (so you can observe the difference between Breadth-First and Depth-First searching).

How to construct a binary tree from just the level order traversal string

Consider a binary tree with the following properties:
An internal node (non-leaf node) has a value 1 if it has two children.
A leaf node has a value 0 since it has no children.
A level order traversal on the tree would generate a string of 1s and 0s (by printing the weird value at each node as they are visited). Now given this string construct the binary tree and perform a post order traversal on the tree. The post order string should be the output of the program.
For example: Input String is 111001000. Create a binary tree from this. Then perform the post order traversal on the tree which would result in an output: 001001011
The "crux" of the problem is to create the binary tree from just the level order string. How would I do this?
Taking your example of level order traversal - 111001000
The tree would be as follows
A
/ \
B C
/\ /\
D E F G
/\
H I
The logic is as follows.
1) Take first bit if its 1 (root) - then next 2^1 are values of children of that parent. So 2nd and 3rd bits are childern of A (root).
2) Go to next bit (1 for B) as its value is also 1 it also has 2 children and then next bit (1 for C) which also has 2 children. Second level is over and as we have 2 1's so 2^2 next bits are for level 3.
3) 111 001000 so this we have traversed and next 4 bits are children on 3rd level. 4th and 5th bits being 0 (D and E are leaf nodes and have no children - These will be children of B) and then F has bit value of 1 so 1110010 00 (bold figures) will be children of F. 7th bit is 0 and so G will also be leaf node.
4) Again loop through or try recusion - From 4th,5th and 6th and 7th bits only one bit is 1 so next 2^1 bits will be in next level and those will be children of F.
Once the tree is made then converting to PostFix is easy.
One possible solution (in less than an hour):
import java.util.ArrayList;
import java.util.List;
public class Main {
private static class Node {
private Node left;
private Node right;
}
private static Node buildTree(String input) {
char chars[] = input.toCharArray();
if (chars.length == 0) {
return null;
} else {
Node root = new Node();
List<Node> nodeList = new ArrayList<Node>();
nodeList.add(root);
int pos = 0;
while (!nodeList.isEmpty()) {
List<Node> nextList = new ArrayList<Node>();
for (Node n: nodeList) {
if (pos >= chars.length) {
throw new RuntimeException("Invalid input string");
}
char c = chars[pos++];
if (c == '1') {
n.left = new Node();
n.right = new Node();
nextList.add(n.left);
nextList.add(n.right);
} else if (c != '0') {
throw new RuntimeException("Invalid input string");
}
}
nodeList = nextList;
}
return root;
}
}
private static String postTraverse(Node n) {
if (n == null) {
return "";
} else if (n.left == null && n.right == null) {
return "0";
} else {
return postTraverse(n.left) + postTraverse(n.right) + "1";
}
}
public static void main(String[] args) {
Node tree = buildTree(args[0]);
System.out.println(postTraverse(tree));
}
}
If it was allowed, I would use a binary heap as a helper here. In a binary heap implemented using a standard table, given an index of an element we can easily calculate its parent's index: int parent = (index-1)/2;. Knowing this, we would need to start at the beginning of our table and do the folowing:
Set the binaryHeap[0] to the first number from the input stream;
for all the remaining elements in input stream:
do{
binaryHeap[heapIndex] = -1;
if (parent(heapIndex) = 1)
binaryHeap[heapIndex] = nextElementFromTheInputStream;
heapIndex++;
}
while(binaryHeap[heapIndex - 1] == 0);
So basically, we move through our table. We initialize each field (except root at 0) to be -1, which means there is no node there. Then we check if the parent of that field was 1. If it was, then we place next element from the input stream on our current index in the heap (heapIndex). If the parent of a current field is 0, we just go further, because that means our parent is a leaf and is not supposed to have any children.
Then we can run post-order algorithm on the heap (probably it would be worth implementing some security-code, so that no element with "-1" is placed in the output stream. Just interpret leftChild(heapIndex) == -1; or rightChild(heapIndex) == -1; to be NULL).
This algorithm is probably quite inefficient in terms of memory, but I hope it is quite easy to understand.
First, I assume that your level order traversal is basically a BFS.
Now, let's have a look at the string. Performing the BFS, we print "1" if the current node's got two sons. Otherwise, it's a leaf and we print 0, terminating the processing of the current branch.
Consequently, during the reverse task, we can remember the list of open branches' last nodes and append the incoming nodes there.
Let's demonstrate this approach on an example:
Level 1:
Tree :
1 - id 0
Open branches : 0 0 (left and right son)
Remaining string : 11001000
*********
Level 2:
Tree :
1
1 1
Open branches : 1 1 2 2
Remaining string : 001000
*********
Level 3:
Tree :
1
1 1
0 0 1 0
Open branches : 5 5
Remaining string : 00
Level 4:
Tree :
1
1 1
0 0 1 0
0 0
No more input, we're done.
Having the tree, the post-order traversal is trivial.
And the code (it assumes that the tree is quite dense, otherwise it's not very memory efficient):
import java.util.ArrayDeque;
import java.util.Queue;
public class Main {
static final int MAX_CONST = 50;
public static void main(String[] args) {
String evilString = "111001000"; // Assuming this string is a correct input
char[] treeRepr = new char[MAX_CONST];
Queue<Integer> q = new ArrayDeque<Integer>();
q.add(0);
for (int i = 0; i < evilString.length(); ++i) {
int index = q.remove();
char ch = evilString.charAt(i);
if (ch == '1') {
q.add(2*(index+1)-1);
q.add(2*(index+1));
}
treeRepr[index] = ch;
// System.out.println(q.size());
}
System.out.println(arrToString(treeRepr, 0, new StringBuilder()));
}
public static StringBuilder arrToString(char[] array, int index, StringBuilder sb) {
if (array[index] == '1')
{
arrToString(array, 2*(index+1)-1, sb);
arrToString(array, 2*(index+1), sb);
}
sb.append(array[index]);
return sb;
}
}
Here is a pretty simple solution. Not really optimal with
respect to memory though, as I build a complete/full tree first
and then I mark which nodes actually exist in our tree. So this
could be optimized a bit, I guess.
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
class Node {
public Node left;
public Node right;
public Integer id;
public boolean exists;
}
public class Test32 {
public static void main(String[] args) {
HashMap<Integer, Node> mp = new HashMap<Integer, Node>();
String str = "110101000";
int sz = (int)Math.pow(2, str.length() + 1);
for (int i=0; i<sz; i++){
Node nd = new Node();
nd.id = i;
mp.put(nd.id, nd);
}
for (int i=0; i<sz; i++){
Node nd = mp.get(i);
if (2*i < sz) nd.left = mp.get(2*i + 1);
if (2*i + 1 < sz) nd.right = mp.get(2*i + 2);
}
Queue<Integer> visit = new LinkedList<Integer>();
visit.add(0); // id = 0;
int j = 0;
int id = -1;
while (!visit.isEmpty()){
id = visit.poll();
if (str.charAt(j) == '1'){
mp.get(id).exists = true;
visit.add(2*id + 1);
visit.add(2*id + 2);
}else{
mp.get(id).exists = true;
}
j++;
}
System.out.println("NODES:");
for (int i=0; i<sz; i++){
if (mp.get(i).exists){
System.out.println(i);
}
}
System.out.println();
System.out.println("EDGES:");
for (int i=0; i<sz; i++){
if (mp.get(i).exists){
if (mp.get(2 * i + 1).exists){
System.out.println(i + " --> " + (2*i+1));
}
if (mp.get(2 * i + 2).exists){
System.out.println(i + " --> " + (2*i+2));
}
}
}
}
}
And here is the same solution simplified edition.
No trees or maps, just a boolean array. If some node
k has children these children are 2*k+1 and 2*k+2.
In the last loop while printing the edges one can also
construct an actual binary tree.
import java.util.LinkedList;
import java.util.Queue;
public class Test32 {
public static void main(String[] args) {
String str = "110101000";
int sz = (int)Math.pow(2, str.length() + 1);
boolean exists[] = new boolean[sz];
Queue<Integer> visit = new LinkedList<Integer>();
visit.add(0); // id = 0;
if (str.charAt(0) == '1'){
exists[0] = true;
}
int j = 0;
int id = -1;
while (!visit.isEmpty()){
id = visit.poll();
if (str.charAt(j) == '1'){
exists[id] = true;
visit.add(2*id + 1);
visit.add(2*id + 2);
}else{
exists[id] = true;
}
j++;
}
// System.out.println("");
System.out.println("NODES:");
for (int i=0; i<sz; i++){
if (exists[i]){
System.out.println(i);
}
}
System.out.println("");
System.out.println("EDGES:");
for (int i=0; i<sz; i++){
if (exists[i]){
if (exists[2*i+1]){
System.out.println(i + " --> " + (2*i+1));
}
if (exists[2*i+2]){
System.out.println(i + " --> " + (2*i+2));
}
}
}
}
}
Conceptually more simpler I think.
import java.util.LinkedList;
import java.util.Queue;
class WeirdBinaryTree
{
static class Node
{
private Node right;
private Node left;
private int weirdValue;
public void setWeirdValue(int value)
{
weirdValue=value;
}
}
private static Node makeTree(String str)throws Exception
{
char[] array=str.toCharArray();
Node root=new Node();
Queue<Node> list=new LinkedList();
list.add(root);
int i=0;
Queue<Node> nextList=new LinkedList<Node>();
while(!list.isEmpty())
{
if(array[i++]=='1')
{
Node temp=list.poll();
temp.left=new Node();
temp.right=new Node();
temp.setWeirdValue(1);
nextList.add(temp.left);
nextList.add(temp.right);
}
else
{
list.poll();
}
if(list.isEmpty())
{
list=nextList;
nextList=new LinkedList<Node>();
}
}
return root;
}
private static void postTraversal(Node localRoot)
{
if(localRoot!=null)
{
postTraversal(localRoot.left);
postTraversal(localRoot.right);
System.out.print(localRoot.weirdValue);
}
}
public static void main(String[] args)throws Exception
{
postTraversal(makeTree("111001000"));
}
}

Categories