dimanche 3 mai 2015

Java Binary Tree Validate

The point of this project is to get an array from the user and use it to create a tree using nodes. The next step is to call a method to check if it represents a Binary tree. I've been working on this for hours and can't seem to find the correct method to check.

Here is my code so far. I have done everything but the isBinaryTree() method to check if it is a Binary tree.

import java.util.Scanner;

public class TestBinaryTree 
{
Node root;

    public void addNode(int key)
    {
        Node newNode = new Node(key);

        if(root == null)
        {
            root = newNode;
        }
        else
        {
            Node focusNode = root;

            Node parent;

            while(true)
            {
                parent = focusNode;

                if(key < focusNode.key)
                {
                    focusNode = focusNode.leftChild;

                    if(focusNode == null)
                    {
                        parent.leftChild = newNode;
                        return;
                    }
                }
                else
                {
                    focusNode = focusNode.rightChild;

                    if(focusNode == null)
                    {
                        parent.rightChild = newNode;
                        return;
                    }
                }
            }
        }
    }

    /*public static boolean isBinaryTree(int rt, int lft, int rght) 
    { 

    }*/

    public static void main(String[] args) 
    {
        int Nroot, Nleft, Nright;

        Scanner input = new Scanner(System.in);
        TestBinaryTree theTree = new TestBinaryTree();

        System.out.println("How many numbers are in the array: ");
        int num = input.nextInt();

        int arr[]=new int[num];

        System.out.println("Enter the numbers: ");
        for(int i=0;i<num;i++)
        {
            arr[i] = input.nextInt();
            theTree.addNode(arr[i]);
        }
    }
}

class Node
{
    int key;

    Node leftChild;
    Node rightChild;

    Node(int key)
    {
        this.key = key;
    }

    public String toString()
    {
        return "Node: " + key;
    }
}

Aucun commentaire:

Enregistrer un commentaire