English 中文(简体)
简称 j树执行
原标题:BinaryTree implementation in java

I have this code for BinaryTree creation and traversal


class Node
{
    Integer data;
    Node left;
    Node right;
    Node()
    {
        data = null;
        left = null;
        right = null;
    }
}
class BinaryTree
{
    Node head;
    Scanner input = new Scanner(System.in);
    BinaryTree()
    {
        head = null;
    }
    public void createNode(Node temp, Integer value) 
    {
        Node newnode= new Node();
        value = getData();
        newnode.data = value;
        temp = newnode;
        if(head==null)
        {
            head = temp;
        }
        System.out.println("If left child exits for ("+value+") enter y else n");
        if(input.next().charAt(0)== y )
        {
            createNode(temp.left, value);
        }
        System.out.println("If right child exits for ("+value+") enter y else n");
        if(input.next().charAt(0)== y )
        {
            createNode(temp.right, value);
        }       
    }
    public Integer getData()
    {
        out.println("Enter the value to insert:");
        return (Integer)input.nextInt();
    }

    public void print()
    {
        inorder(head);
    }
    public void inorder(Node node)
    {
        if(node!=null)
        {
            inorder(node.left);
            System.out.println(node.data);
            inorder(node.right);
        }
        else
            return;
    }
}

class BinaryTreeWorker
{
    static BinaryTree treeObj = null;
    static Scanner input = new Scanner(System.in);
    public static void displaymenu()
    {
        int choice;
        do{
            out.print("
 Basic operations on a tree:");
            out.print("
 1. Create tree  
 2. Insert 
 3. Search value 
 4. print list
 Else. Exit 
 Choice:");
            choice = input.nextInt();

            switch(choice)
            {
                case 1:
                    treeObj = createBTree();
                    break;
                case 2:
                    treeObj.createNode(null, null);
                    break;
                case 3:
                    //searchnode();
                    break;
                case 4:
                    treeObj.print();
                    break;
                default:
                    return;
            }       
        }while(true);
    }
    public static BinaryTree createBTree()
    {
        return new BinaryTree();
    }
    public static void main(String[] args)
    {
        displaymenu();
    }
}

它汇编并运行。 但我认为,秩序混乱是错误的。

我 below树如下:

    2
1       3

But it prints only 2.

最佳回答

I have tried solving the problem your way and I have pasted the solution below.. Though I haven t tested it thoroughly so it might fail in some edge condition.. But I have tested it for one case. Kindly let me know if it fails in some scenario. I would appreciate others help in making this answer better. I agree that this solution is not the most ideal way to code a Binary Tree but it wont hurt this way if some one is just practicing..

import java.util.Scanner;


class Node
{
    Integer data;
    Node left;
    Node right;
    Node()
    {
        data = null;
        left = null;
        right = null;
    }
}
class BinaryTree
{
    Node head;
    Scanner input = new Scanner(System.in);
    BinaryTree()
    {
        head = null;
    }

    public void createNode(Node temp,Node newnode) 
    {

        if(head==null)
        {
            System.out.println("No value exist in tree, the value just entered is set to Root");
            head = newnode;
            return;
        }
        if(temp==null)
            temp = head;

        System.out.println("where you want to insert this value, l for left of ("+temp.data+") ,r for right of ("+temp.data+")");
        char inputValue=input.next().charAt(0); 
        if(inputValue== l ){
            if(temp.left==null)
            {
                temp.left=newnode;
                System.out.println("value got successfully added to left of ("+temp.data+")");
                return;
            }else  {
                System.out.println("value left to ("+temp.data+") is occupied 1by ("+temp.left.data+")");
                createNode(temp.left,newnode);
            }
        }
        else if(inputValue== r )
        {
            if(temp.right==null)
            {
                temp.right=newnode;
                System.out.println("value got successfully added to right of ("+temp.data+")");
                return;

            }else  {
                System.out.println("value right to ("+temp.data+") is occupied by ("+temp.right.data+")");
                createNode(temp.right,newnode);
            }

        }else{
            System.out.println("incorrect input plz try again , correctly");
            return;
        }

    }
    public Node generateTree(){
        int [] a = new int[10];
        int index = 0; 
        while(index<a.length){
            a[index]=getData();
            index++;
        }
        if(a.length==0 ){
            return null;
        }
        Node newnode= new Node();
        /*newnode.left=null;
        newnode.right=null;*/
        return generateTreeWithArray(newnode,a,0);

    }
    public Node generateTreeWithArray(Node head,int [] a,int index){

        if(index >= a.length)
            return null;
        System.out.println("at index "+index+" value is "+a[index]);
        if(head==null)
            head= new Node();
        head.data = a[index];
        head.left=generateTreeWithArray(head.left,a,index*2+1);
        head.right=generateTreeWithArray(head.right,a,index*2+2);
        return head;
    }

    public Integer getData()
    {
        System.out.println("Enter the value to insert:");
        return (Integer)input.nextInt();
    }

    public void print()
    {
        inorder(head);
    }
    public void inorder(Node node)
    {
        if(node!=null)
        {
            inorder(node.left);
            System.out.println(node.data);
            inorder(node.right);
        }
        else
            return;
    }
}

public class BinaryTreeWorker
{
    static BinaryTree treeObj = null;
    static Scanner input = new Scanner(System.in);
    public static void displaymenu()
    {
        int choice;
        do{
            System.out.print("
 Basic operations on a tree:");
            System.out.print("
 1. Create tree  
 2. Insert 
 3. Search value 
 4. print list
 5. generate a tree 
 Else. Exit 
 Choice:");
            choice = input.nextInt();

            switch(choice)
            {
                case 1:
                    treeObj = createBTree();
                    break;
                case 2:
                    Node newnode= new Node();
                    newnode.data = getData();
                    newnode.left=null;
                    newnode.right=null;
                    treeObj.createNode(treeObj.head,newnode);
                    break;
                case 3:
                    //searchnode();
                    break;
                case 4:
                    System.out.println("inorder traversal of list gives follows");
                    treeObj.print();
                    break;
                case 5:
                    Node tempHead = treeObj.generateTree();
                    System.out.println("inorder traversal of list with head = ("+tempHead.data+")gives follows");
                    treeObj.inorder(tempHead);
                    break;
                default:
                    return;
            }       
        }while(true);
    }
    public static Integer getData()
    {
        System.out.println("Enter the value to insert:");
        return (Integer)input.nextInt();
    }
    public static BinaryTree createBTree()
    {
        return new BinaryTree();
    }
    public static void main(String[] args)
    {
        displaymenu();
    }
}

[Update] : Updated the code to generate a binary tree using an array. This will involve less user interaction.

问题回答

Best way to implement Binary Tree in Java with all the traverse types and test cases as below

package com.nitin.tree;

public class Tree
{
    private Node parent;

    private int  data;

    private int  size = 0;

    public Tree() {
        parent = new Node(data);
    }

    public void add(int data) {

        if (size == 0) {
            parent.data = data;
            size++;
        } else {
            add(parent, new Node(data));
        }
    }

    private void add(Node root, Node newNode) {

        if (root == null) {
            return;
        }

        if (newNode.data < root.data) {

            if (root.left == null) {
                root.left = newNode;
                size++;
            } else {
                add(root.left, newNode);
            }
        } else {

            if (root.right == null) {
                root.right = newNode;
                size++;
            } else {
                add(root.right, newNode);
            }
        }
    }

    public int getLow() {

        Node current = parent;

        while (current.left != null) {
            current = current.left;
        }

        return current.data;
    }

    public int getHigh() {

        Node current = parent;

        while (current.right != null) {
            current = current.right;
        }

        return current.data;
    }

    private void in(Node node) {

        if (node != null) {

            in(node.left);
            System.out.print(node.data + " ");
            in(node.right);
        }
    }

    private void pre(Node node) {

        if (node != null) {

            System.out.print(node.data + " ");
            pre(node.left);
            pre(node.right);
        }
    }

    private void post(Node node) {

        if (node != null) {

            post(node.left);
            post(node.right);
            System.out.print(node.data + " ");
        }
    }

    public void preorder() {

        System.out.print("Preorder Traversal->");
        pre(parent);
        System.out.println();
    }

    public void postorder() {

        System.out.print("Postorder Traversal->");
        post(parent);
        System.out.println();
    }

    public void inorder() {

        System.out.print("Inorder Traversal->");
        in(parent);
        System.out.println();
    }

    private class Node {

        Node left;

        Node right;

        int  data;

        public Node(int data) {
            this.data = data;
        }
    }

    public String toString() {

        Node current = parent;
        System.out.print("Traverse From Left ");

        while (current.left != null && current.right != null) {

            System.out.print(current.data + "->[" + current.left.data + " " + current.right.data + "] ");
            current = current.left;
        }

        System.out.println();
        System.out.print("Traverse From Right ");

        current = parent;

        while (current.left != null && current.right != null) {

            System.out.print(current.data + "->[" + current.left.data + " " + current.right.data + "] ");
            current = current.right;
        }

        return "";
    }

    public static void main(String af[]) {

        Tree t = new Tree();

        t.add(40);
        t.add(25);
        t.add(78);
        t.add(10);
        t.add(32);
        t.add(50);
        t.add(93);
        t.add(3);
        t.add(17);
        t.add(30);
        t.add(38);

        System.out.println(t.getLow());

        System.out.println(t.getHigh());

        System.out.println("Size-" + t.size);

        System.out.println(t);

        t.inorder();

        t.preorder();

        t.postorder();
    }
}

您的问题载于<代码> 公开无效创建Nodes(Node temp, T data)功能。 你用一个参数通过同一类变量的温带。 首先,我不认为你自己需要不同类别。 这种方法中排出节奏的二分之一只具有地方效应——你在<代码>temp参数中松散信息,但设定了节奏,不会对这种方法的价值产生怀疑。 我建议你重写这一方法,使之回到新创建的节点,并将这个点子分配给<条码>、和<条码>当地<条码>的右边/代码>。 这样,这些变化就会蔓延。

另一种类型的树木产出:

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

protected void visit(BSTNode<T> p) 
{
 System.out.println("Node: " + p.el + "Left Side:" + (p.left!=null?p.left.el:"null") +  
 "Right          Side:" + (p.right!=null?p.right.el:"null"));
}

I ve改变了宾塔雷类,如下。 尤其见create Node方法上的改动。

如前所述,问题在于,当你作为论据通过create Node方法时,你的提法就一直存在。 这一变化只是地方性的。 你们在重新创造节点时,必须重新明确提及这种方法本身。

public Node createNode() 
{

    Integer value = getData();


    Node temp = new Node(value);
    if(head==null)
    {
        head = temp;
    }
    System.out.println("Do you want to add left branch on node("+value+")? Enter y/n");
    if(input.next().charAt(0)== y )
    {
        temp.left=createNode();
    }
    System.out.println("Do you want to add right branch on node("+value+")? Enter y/n");
    if(input.next().charAt(0)== y )
    {
        temp.right=createNode();
    }     

    return temp;
}

产出如下:

 Basic operations on a tree:
 1. Create tree  
 2. Insert 
 3. Search value 
 4. print list
 Else. Exit 
 Choice:1

 Basic operations on a tree:
 1. Create tree  
 2. Insert 
 3. Search value 
 4. print list
 Else. Exit 
 Choice:2
Enter the value to insert:
10
Do you want to add left branch on node(10)? Enter y/n
y
Enter the value to insert:
20
Do you want to add left branch on node(20)? Enter y/n
n
Do you want to add right branch on node(20)? Enter y/n
n
Do you want to add right branch on node(10)? Enter y/n
y
Enter the value to insert:
30
Do you want to add left branch on node(30)? Enter y/n
n
Do you want to add right branch on node(30)? Enter y/n
n

 Basic operations on a tree:
 1. Create tree  
 2. Insert 
 3. Search value 
 4. print list
 Else. Exit 
 Choice:4
20
10
30

我希望这将对后来的某个人有所帮助(即使这已晚了3年)。 我刚刚开始亲眼学习 Bin树。 我实际上计划把这作为完成更多相关任务的基础!

我改变了“诺德”方法,以便:

public Node createNode(Node temp, Integer value) 
{
    Node newnode = new Node();
    value = getData();
    newnode.data = value;
    temp = newnode;
    if(head == null)
    {
        head = temp;
    }
    System.out.println("If left child exits for ("+value+") enter y else n");
    if(input.next().charAt(0) ==  y )
    {
        newnode.left = createNode(newnode.left, value);
    }
    System.out.println("If right child exits for ("+value+") enter y else n");
    if(input.next().charAt(0) ==  y )
    {
        newnode.right = createNode(newnode.right, value);
    } 
    return newnode;
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签