繁体   English   中英

二叉树:插入节点算法

[英]Binary tree: insert node algorithm

我正在尝试实现一个二叉树(如果它是普通的二叉树或二叉搜索树,则不重要),并且我在创建节点并将其链接到树的功能上遇到了麻烦。
这是我到目前为止编写的代码:

class BinaryTree {
    class Node {
        char data;

        Node* leftChild;
        Node* rightChild;

        Node(char d, Node* lc, Node* rc):
            data(d), leftChild(lc), rightChild(rc) {}
    } *head;
    int treeSize;
public:
    BinaryTree(): head(0), treeSize(0) {}

    // totally wrong code
    void createNode(char dat) {
        if (head->data < dat)
            head->leftChild = new Node(dat, 0, 0);
        if (head->rightChild == 0)
            head->rightChild = new Node(dat, 0, 0);
        if (head == 0) {
            head = new Node(dat, head, head);
        }
    }
};

好吧,我想使用链接列表来实现二叉树,但是在这种情况下,问题将是head指针指向最后添加的节点之一,而不是根节点。 以这种方式使用链接列表的另一个问题可能是找到要在其中添加新节点的节点的空子节点。
有人可以帮助我,也许会建议一个更好的方法来实现二叉树?

注意:我计划将此类作为template ,char只是用于即时尝试。

我认为您采取了正确的方法,但是没有完成。 您的方法可能如下所示:

void addNode( char data ) {
    // when root is uninitialized
    if ( NULL == head ) {
        head = new Node( data, NULL, NULL );
    } else {
        Node *currentNode = head;
        // search for the place to insert the new value
        while ( true ) {
            if ( currentNode->data < data ) {
                // if the current node already has left child
                // so we concern it further
                if ( NULL != currentNode->leftChild ) {
                    currentNode = currentNode->leftChild;
                    continue;
                // if the current node has no left child
                // so we create it with the new value
                } else {
                    currentNode->leftChild = new Node( data, NULL, NULL );
                    return;
                }
            } else {
                // similarly for the value that should be inserted into
                // right subtree
                if ( NULL != currentNode->rightChild ) {
                    currentNode = currentNode->rightChild;
                    continue;
                } else {
                    currentNode->rightChild = new Node( data, NULL, NULL );
                    return;
                }
            }
        }
    }
}

这只是我注意到的几件事:

  1. 您应该先检查head!= null,否则您的第一个createNode()将崩溃。所有其他分支应位于“ else”中。

  2. 为了代码清晰和/或作为国际维护程序员赞赏运动的一部分,您的最后一个(或首先要说的)新Node(日期,头,头)应为新Node(日期,0、0)。

  3. 您可能想增加treeSize。

否则,您将走上正确的道路。 继续。

我假设这是某种形式的家庭作业,所以我认为重要的是要强调基础知识,让您弄清楚其余的内容。 因为它是任何遍历树的起点,所以Head永远都不应更改,除非您要删除根Node。 任何遍历都应该由另一个Node对象完成,该对象可以(并且可能经常)在每次函数调用结束时超出范围,而在程序中没有任何副作用。

正如已经指出的那样,您需要考虑将head = NULL作为第一个条件的情况,然后处理随后的head!= NULL遍历。 对于插入,您必须考虑到插入的方式,并正确链接到树的其他元素。 记住,叶子是其中左右数据成员为NULL的任何Node对象,可能会有所帮助。

祝您程序顺利。

暂无
暂无

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

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