Tuesday, 28 November 2017

Java Program to Perform Preorder Non-Recursive Traversal of a Given Binary Tree


Code:

import java.util.Scanner;
import java.util.Stack;

class BinarySearchTreeNode
{
    BinarySearchTreeNode left, right;
    int                  data;

    public BinarySearchTreeNode()
    {
        left = null;
        right = null;
        data = 0;
    }

    public BinarySearchTreeNode(int n)
    {
        left = null;
        right = null;
        data = n;
    }

    public void setLeft(BinarySearchTreeNode n)
    {
        left = n;
    }

    public void setRight(BinarySearchTreeNode n)
    {
        right = n;
    }

    public BinarySearchTreeNode getLeft()
    {
        return left;
    }

    public BinarySearchTreeNode getRight()
    {
        return right;
    }

    public void setData(int d)
    {
        data = d;
    }

    public int getData()
    {
        return data;
    }
}

class BinarySearchTreeOperations
{
    private BinarySearchTreeNodes root;

    public BinarySearchTreeOperations()
    {
        root = null;
    }

    public boolean isEmpty()
    {
        return root == null;
    }

    public void insert(int data)
    {
        root = insert(root, data);
    }

    private BinarySearchTreeNodes insert(BinarySearchTreeNodes node, int data)
    {
        if (node == null)
            node = new BinarySearchTreeNodes(data);
        else
        {
            if (data <= node.getData())
                node.left = insert(node.left, data);
            else
                node.right = insert(node.right, data);
        }
        return node;
    }

    public void preorder()
    {
        preorder(root);
    }

    private void preorder(BinarySearchTreeNodes r)
    {
        Stack s = new Stack();
        s.push(r);
        while (!s.empty())
        {
            r = s.pop();
            System.out.print(r.data + " ");
            if (r.right != null)
                s.push(r.right);
            if (r.left != null)
                s.push(r.left);
        }
    }
}

public class Preorder_NonRecursive_BST
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        BinarySearchTreeOperations bst = new BinarySearchTreeOperations();
        System.out.println("Enter the first 10 elements of the tree\n");
        int N = 10;
        for (int i = 0; i < N; i++)
            bst.insert(scan.nextInt());

        System.out.print("\nPre order  : ");
        bst.preorder();

        scan.close();
    }
}


Output:

Enter the first 10 elements of the tree

12 4 10 13 15 46 78 98 45 12

Pre order  : 12 4 10 12 13 15 46 45 78 98


More Java Programs:
















100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...