簡體   English   中英

二叉搜索樹“棧”解釋

[英]Binary Search Tree "stack" explanation

我在 C# 中有一個非常簡單的 BST 實現。 編碼:

class Node
{
    public int? value;
    public Node parent;
    public Node left;
    public Node right;

    public Node(int? value, Node parent = null)
    {
        this.value = value;
        this.parent = parent;
    }
}

class BST
{
    public Node root;
    public List<Node> tree = new List<Node>();

    public BST(int? value = null)
    {
        if (value != null)
        {
            this.root = new Node(value);
            this.tree.Add(this.root);
        }
    }

    public Node insert(int value)
    {
        Node node = this.root;

        if (node == null)
        {
            this.root = new Node(value);
            this.tree.Add(this.root);

            return this.root;
        }

        while (true)
        {
            if (value > node.value)
            {
                if (node.right != null)
                {
                    node = node.right;
                }
                else
                {
                    node.right = new Node(value, node);
                    node = node.right;
                    break;
                }
            }
            else if (value < node.value)
            {
                if (node.left != null)
                {
                    node = node.left;
                }
                else
                {
                    node.left = new Node(value, node);
                    node = node.left;
                    break;
                }
            }
            else
            {
                break;
            }
        }
        return node;
    }
}

class Program
{
    static void Main()
    {
        BST superTree = new BST(15);
        superTree.insert(14);
        superTree.insert(25);
        superTree.insert(2);
    }
}

我的問題是關於 BST 類的“插入”方法。

當我在 main 方法中調用它時,它的“返回”究竟是如何工作的? 它怎么知道把那個“節點”放在“左邊”? 我沒有在任何地方引用“root.left”,但它以某種方式被正確插入。

我在某個時候意識到那里發生了某種遞歸,但是已經過了 6 個小時,我仍然無法理解這種方法是如何正常工作的。

我感謝對“插入”方法的任何解釋。謝謝。

Node node = this.root;

由於這一行,您的代碼總是從根開始。 這是只有在node不再為空即node被重新分配給根以外的東西。 其余代碼適用於node.left ,但由於您的代碼以上述root開頭,因此node.left實際上在開頭引用了root

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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