Binary Tree Traversal

 public class TreeNode {

    Integer value;
TreeNode left;
TreeNode right;

public TreeNode(Integer value) {
this.value = value;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

public TreeNode getLeft() {
return left;
}

public void setLeft(TreeNode left) {
this.left = left;
}

public TreeNode getRight() {
return right;
}

public void setRight(TreeNode right) {
this.right = right;
}
}

public class TreeTraversal {

public static TreeNode createTree()
{
TreeNode rootNode = new TreeNode(9);
TreeNode node1 = new TreeNode(7);
TreeNode node2 = new TreeNode(10);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(8);

rootNode.setLeft(node1);
rootNode.setRight(node2);
node1.setLeft(node3);
node1.setRight(node4);


return rootNode;
}

public static void preOrder(TreeNode rootNode)
{
if(rootNode==null) return;
System.out.println("Value-->"+rootNode.getValue());
preOrder(rootNode.left);
preOrder(rootNode.right);

}

public static void postOrder(TreeNode rootNode)
{
if(rootNode==null) return;
postOrder(rootNode.left);
postOrder(rootNode.right);
System.out.println("Value-->"+rootNode.getValue());
}

public static void inOrder(TreeNode rootNode)
{
if(rootNode==null) return;
inOrder(rootNode.left);
System.out.println("Value-->"+rootNode.getValue());
inOrder(rootNode.right);
}

public static void main(String args[])
{
TreeNode rootNode = createTree();

System.out.println("PRE ORDER");
preOrder(rootNode);
System.out.println("POST ORDER");
postOrder(rootNode);
System.out.println("IN ORDER");
inOrder(rootNode);
System.out.println("Find Even Numbers");
findEvenNumbers(rootNode);
}

public static void findEvenNumbers(TreeNode node)
{
if(node==null) return;
if(node.getValue()%2==0) System.out.println(node.getValue());
findEvenNumbers(node.left);
findEvenNumbers(node.right);
}
}

Output
PRE ORDER
Value-->9
Value-->7
Value-->3
Value-->8
Value-->10
POST ORDER
Value-->3
Value-->8
Value-->7
Value-->10
Value-->9
IN ORDER
Value-->3
Value-->7
Value-->8
Value-->9
Value-->10
Find Even Numbers
8
10

Comments

Popular posts from this blog

Java 8 : Find the number starts with 1 from a list of integers

How to prevent Singleton Class from Reflection and Serialization

Optional Vs Null Check