JAVA program to perform iterative preorder traversal

Posted On // Leave a Comment

CODE:

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

public class iterPre{

    static Scanner in = new Scanner(System.in);

        static node inputTree(){
        node temp=new node();
        System.out.print("Enter the value: ");
        temp.data=in.nextInt();
        System.out.print("Enter y if the node "+temp.data+" has left subtree: ");
        if(in.next().charAt(0)=='y')
            temp.left=inputTree();
        else
            temp.left=null;
        System.out.print("Enter y if the node "+temp.data+" has right subtree: ");
        if(in.next().charAt(0)=='y')
            temp.right=inputTree();
        else
            temp.right=null;
        return temp;
    }

    static void iterPreorder(node root){
        if(root == null)
            return;
        node tmp = new node();
        Stack<node> s = new Stack<node>();
        s.push(root);
        while (s.isEmpty()==false) {
            tmp = s.pop();
            System.out.print("\t"+tmp.data);
            if(tmp.right != null)
                s.push(tmp.right);
            if(tmp.left != null)
                s.push(tmp.left);
        }
    }

    public static void main(String[] args) {
        node root = new node();
        root = inputTree();
        iterPreorder(root);
    }

}

0 comments :

Post a Comment