在Java中二叉树实现 [英] BinaryTree implementation in java

查看:124
本文介绍了在Java中二叉树实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个$ C $下二叉树建立和遍历

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("\n Basic operations on a tree:");
            out.print("\n 1. Create tree  \n 2. Insert \n 3. Search value \n 4. print list\n Else. Exit \n 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();
    }
}

编译和运行。不过,我觉得有什么不对的序遍历。

It compiles and runs. But I think there is something wrong with the inorder traversal.

我在下面的树,


    2
1       3

但只有二打印。

But it prints only 2.

推荐答案

我曾尝试解决问题的方式,我已经贴在下面。该解决方案虽然我没有测试它彻底,因此可能会在一些边缘状态失败..但是我已经测试了它的一个案例。请让我们如果不能在某些情况下我知道了。我想AP preciate其他人在做这个答案更好的帮助。我同意这个解决方案并不是最理想的方式codeA二叉树,但它不会伤害这样,如果有一个人是刚刚练..

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("\n Basic operations on a tree:");
            System.out.print("\n 1. Create tree  \n 2. Insert \n 3. Search value \n 4. print list\n 5. generate a tree \n Else. Exit \n 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();
    }
}

[更新] :更新了code生成使用数组二叉树。这将涉及较少的用户交互。

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

这篇关于在Java中二叉树实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆