使用Java在二叉树中插入不起作用 [英] inserting in binary tree doesn't work using java

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

问题描述

我目前正在使用Java学习树木我在这里发生一些错误在二叉树中插入项目我不明白为什么它不起作用

I'm currently learning about trees using java and i have some errors going on here in the insertion of items in a binary tree I don't why it doesn't work

这是代码:树节点:

public class TNode {
    int data;
    TNode left;
    TNode right;

    public TNode(int data) {
        this.data = data;
        left = null;
        right = null;
    }
}

树类:

public class Tree {
    TNode root;

    public Tree(){
        root = null;
    }

    public TNode insertNode(TNode item, int d) {
        if (item == null) {
            return new TNode(d);
        }

         if (d < item.data) {
            item.left = insertNode(item, d);
        }

        if (d > item.data) {
            item.right = insertNode(item, d);
        } else {
            return item;
        }

        return item;
    }

    public void add(int d) {
        insertNode(root, d);
    }
}

每当我添加一个项目时,根都将保持为空,而没有右边或左边的项目如果有人可以帮助我,我将非常感激

Whenever I add an item the root remains null with no right or left items if someone can help I'll be really thankful

推荐答案

root 始终为null,因为您从未为其分配值.

root is always null because you never assign value to it.

您可以添加到方法检查的开头并进行分配

you can add to the beginning of your method check and assign it

public TNode insertNode(TNode item, int d){
    if(item == null){
        TNode node = new TNode(d);
        if (root == null) { 
            root = node;
        }
        return node
    }
    ... rest of method isn't changed...

此外,在递归时,您应该使用适当的子节点进行呼叫,而不是始终使用 item 进行呼叫,因此第一种情况是:

Also when you are recursing you should make a call with a proper child node instead of always calling with item, so for example first case would be:

    item.left = insertNode(item.left, d);

对于第二种情况,您只需使用 item.right .

For second case you would just use item.right instead.

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

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