二叉树 - 按顺序排序

时间:2017-05-06 20:33:08

标签: java data-structures binary-tree

我在二叉树分配中有一个快速的问题。我不知道如何修复函数按顺序对二叉树进行排序并打印出来。

错误

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The method inOrder(Node) in the type BinaryTree 
     is not applicable for the arguments ()
    at BinaryTreeTester.main(BinaryTreeTester.java:21)

方法声明

// This function should sort the tree in order and print it
public void inOrder(Node current)
{
    if (current != null)
    {
        inOrder(current.left);
        System.out.println(current.data);
        inOrder(current.right);
    }
}

代码

BinaryTree t1 = new BinaryTree();

// Test insert functions
t1.insert(100);
t1.insert(50);
t1.insert(175);
t1.insert(200);
t1.insert(150);

// Test displayInOrder and displayPreOrder
System.out.println("InOrder: ");
t1.inOrder(); // this is the line that causes the error

我从这个错误中理解的是,因为inOrder(Node)方法需要一个Node类型的参数,所以语句" t1.inOrder()"因为没有使用参数而导致问题。

插入方法

public void insert(int n)
    {
        // If empty -> add new element as root node
        // if root not empty -> traverse

        Node current = root; // set current to root
        Node newNode = new Node(); // create newNode 

        newNode.data = n; // set the data of newNode to n
        newNode.left = null;
        newNode.right = null;

        if(root == null)  // check if tree is empty
            root = newNode; // if yes, set root to newNode
        else
            while(true)     
                if(newNode.data > current.data)
                    if(current.right == null)
                    {
                        current.right = newNode;
                        break;
                    }
                    else
                        current = current.right;
                else
                    if(current.left == null)
                    {
                        current.left = newNode;
                        break;
                    }
                    else
                        current = current.left;
    }

我无法更改代码文件,只能解决函数本身问题。关于如何解决这个问题的任何建议?

3 个答案:

答案 0 :(得分:0)

inOrder的方法签名需要将Node 引用作为参数传递给方法,但是当您调用inOrder方法时re not 传入必需的参数(Node引用),我认为该参数应该是根Node

解决方案是您需要将引用传递给Node的根BinaryTree作为inOrder方法的参数。

t1.inOrder(t1.root);

根据您的评论,您希望调用inOrder方法而不传入类型为Node的参数。这很容易,你要做的就是创建另一个不带参数的方法,但会调用带参数的方法并传入适当的Node(root)。

答案 1 :(得分:0)

由于这是一项任务,我不会提供代码,但会提供一些(希望)有用的提示。

在Java中,只要签名不同,就可以多次声明相同的方法。

如果提供的测试人员要求声明零参数inOrder方法,那么您应该声明它!

现在,您已经有一个单参数inOrder方法接受Node对象作为参数 - 这是启动有序遍历的节点。

如何在新的零参数inOrder中使用此方法开始在树的根处进行有序遍历?

答案 2 :(得分:0)

(代表OP发布)

以下代码完美无缺。感谢您的指导和分享。

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

public void inOrder(Node current)   
{
    if (current != null)
    {   
        inOrder(current.left);
        System.out.println(current.data);   
        inOrder(current.right);
    }
}