Monday, March 7, 2022

Traversals in Binary Tree





package pep.Day31;

import java.util.Stack;

public class Traversals_in_BinaryTree {
private static class Pair {
Node node;
int state;

Pair(Node node, int state) {
this.node = node;
this.state = state;
}
}

private static class Node {
int data;
Node left;
Node right;

Node(int data, Node left, Node right) {
this.data = data;
this.left = left;
this.right = right;
}

}

public static Node construct(Integer[] arr) {
Stack<Pair> stack = new Stack<>();
Node root = new Node(arr[0], null, null);
Pair rootPair = new Pair(root, 1);
stack.push(rootPair);

int idx = 0;
while (stack.size() > 0) {
Pair top = stack.peek();
if (top.state == 1) {
idx++;
if (arr[idx] != null) {
top.node.left = new Node(arr[idx], null, null);
Pair lp = new Pair(top.node.left, 1);
stack.push(lp);
} else {
top.node.left = null;
}

top.state++;
} else if (top.state == 2) {
idx++;
if (arr[idx] != null) {
top.node.right = new Node(arr[idx], null, null);
Pair rp = new Pair(top.node.right, 1);
stack.push(rp);
} else {
top.node.right = null;
}

top.state++;
} else {
stack.pop();
}
}
return root;
}

public static void display(Node node) {
if (node == null)
return;
String str = "";
str += node.left == null ? "." : node.left.data;
str += " <- " + node.data + " -> ";
str += node.right == null ? "." : node.right.data;

System.out.println(str);
display(node.left);
display(node.right);
}

public static void main(String[] args) {
Integer[] arr = {50, 25, 12, null, null, 37, 30, null, null, null,
75, 62, null, 70, null, null, 87, null, null};

Node root = construct(arr);
//display(root);

traversal(root);

}

private static void traversal(Node node) {
if (node == null)
return;

System.out.println(node.data + " in pre-order"); //euler left - pre
traversal(node.left);
System.out.println(node.data + " in in-order"); //euler between - in
traversal(node.right);
System.out.println(node.data + " in post-order"); //euler right - post
}
}




No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...