簡體   English   中英

二進制搜索樹查找父節點

[英]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小於xt.leftChildNULL的話,你在重演insert功能。 在遞歸調用中,由於insert的第二個參數為NULL您將創建一個新節點並將其返回,然后將其保存在AleftChild指針中(返回時)。 從遞歸調用返回后,執行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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM