简体   繁体   English

二叉树-如何删除元素; 爪哇

[英]Binary Tree- How to delete elements; java

node root=null;

public node delete(node node, int val) {
    if(node == null) {
      return node;
    }

    if(val < node.value) {
      node.left= delete(node.left, val);
    } else if(val > node.value) {
      node.right= delete(node.right, val);
    } else {
      if(node.left== null || node.right== null) {
        node temp = node.left!= null ? node.left: node.right;

        if(temp == null) {
          return null;
        } else {
          return temp;
        }
      } else {
    node next = getSuccessor(node);
        node.value= next.value;
        node.right= delete(node.right, next.value);
        return node;
      }
    }

    return node;
  }
public node getSuccessor(node node) {
    if(node == null) {
      return null;
    }

    node temp = node.right;

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

    return temp;
  }

this is my code and this is the class for the nodes:这是我的代码,这是节点的类:

public class node {
    int value;
   node left;
   node right;
}

I already have a working code to add values.我已经有一个工作代码来添加值。 the problem is, when i add values, and try to delete some of them with the code i just wrote here, it's not working.问题是,当我添加值并尝试使用我刚刚在这里编写的代码删除其中一些值时,它不起作用。 this is what i put in main class when i try to delete a value:这是我在尝试删除值时放入主​​类的内容:

binarytree tree= new binarytree;
node root=null;
root=tree.delete(root,4);

does anyone have any idea what could be wrong?有谁知道什么可能是错的? am i missing a function that refers to the delete one or something like that?我是否缺少一个引用删除或类似功能的函数? please note i'm new to java so if you want to help me treat me as a beginner i'd really appreciate if someone could help me make my delete function work because now it's not doing anything at all...请注意,我是 Java 新手,所以如果您想帮助我将我视为初学者,如果有人能帮助我使我的删除功能正常工作,我将不胜感激,因为现在它根本没有做任何事情...

EDIT:编辑:

Code to add values:添加值的代码:

void recadd(node a, int val) {
    if (val<a.value) {
        if (a.left==null){
            a.left=new node (val);
        }
    }
    else
    {
        if(a.right==null) {
            a.right=new node(val);
        }
        else {
            recadd(a.right, val);
        }
    }
}

the code i use to call the add function:我用来调用 add 函数的代码:

void add(int val){
    node k = new node (val);
if (root==null)
{
    root = k;
}
else
{
    recadd(root, val);
}
}

as stated before, i can add values just fine, the problem occurs when i try to delete them.如前所述,我可以添加值就好了,当我尝试删除它们时会出现问题。

Your code should work.您的代码应该可以工作。 Maybe something is wrong with how you are inserting elements.也许您插入元素的方式有问题。 Can you please share your full code?你能分享你的完整代码吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM