[英]Binary Search Tree finding a parent node
我有这段代码,我想知道插入后是否给出了左右孩子的确切父代,所以我制作了这段代码,但不确定是否可以得到正确的父代。
public Node insert(int x, Node t)
{
if (t == null)
{
t = new Node(x, null, null);
}
else if (x < t.iData) {
t.leftChild = insert(x, t.leftChild);
t.parent.leftChild = t ;
}
else if (x > t.iData) {
t.rightChild = insert(x, t.rightChild);
t.parent.rightChild = t ;
}
else ; // Duplicate; do nothing
return t;
}
public class Node {
int iData ;
Node leftChild ;
Node rightChild ;
Node parent;
public Node(int iData)
{
this.iData = iData;
leftChild=null;
rightChild=null;
parent=null;
}
public Node(int iData, Node leftChild, Node rightChild) {
this.iData = iData;
this.leftChild = leftChild;
this.rightChild = rightChild;
parent=null;
}
}
我在代码中看到的唯一问题是,当您尝试添加新添加的节点的父代时。 考虑这两行::
t.leftChild = insert(x, t.leftChild);
t.parent.leftChild = t;
考虑你是一个节点上说, 一个其iData
小于x
和t.leftChild
是NULL
的话,你在重演insert
功能。 在递归调用中,由于insert
的第二个参数为NULL
您将创建一个新节点并将其返回,然后将其保存在A的leftChild
指针中(返回时)。 从递归调用返回后,执行t.parent.leftChild = t;
这实际上意味着,你去parent
A和修改leftChild
中的parent
A的,而不是新添加的节点,这没有任何意义要什么给你正在尝试做的母公司。 因此,正确的方法是更改将父节点分配给此的行:
t.leftChild.parent = t; //when x < iData
// Now you are changing the parent of the leftChild of A
同样
t.rightChild.parent = t; //when x > iData
但是,考虑到树很大,您必须插入一个节点,以便插入一个节点并为其分配父值,按照您编写的代码,您将把节点的parent
值重新分配给已经存在的对象被分配之前,您只是在浪费时间。 一种更合适的方法是:
void insert(Node t, int x) {
if(t == NULL) { // In case the root of the tree is NULL
t = new Node(x);
} else if(t.iData == x) {
return; // Do nothing
} else if(t.iData > x) { //left branch
if(t.leftChild == NULL) { // This is the place where you have to insert node
t.leftChild = new Node(x);
t.leftChild.parent = t;
} else { // You have more branches to traverse
insert(t.leftChild, x);
// Here you do not unnecessarily assign parent values again.
}
} else { //t.iData < x
if(t.rightChild== NULL) { // This is the place where you have to insert node
t.rightChild= new Node(x);
t.rightChild.parent = t;
} else { // You have more branches to traverse
insert(t.rightChild, x);
// Here you do not unnecessarily assign parent values again,
// when you return from recursion.
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.