0
//binary_tree.h file
typedef struct node node;

struct node
{   node():left(0), right(0), value(-1){};
    ~node(){if(left) delete left; if(right) delete right;};
    node *left;
    node *right;
    int value;
};

inline void insert_node(node **root, node *new_node)
{
    assert(new_node != NULL);
    if(*root == NULL)
    {
        *root = new_node;
    }
    else
    {
        node *itr = *root;
        while(1)
        {
            if(itr->value > new_node->value)
                itr = itr->left;
            else
                itr = itr->right;
            if(!itr)
            {
                itr = new_node;
                break;
            }
        }
    }
}

inline void inorder_print(node *root)
{
    if(!root) return;
    inorder_print(root->left);
    printf("%d\n", root->value);
    inorder_print(root->right);
}

//main.cpp file
#include "binary_tree.h"

int main()
{
    node *node1 = new node();
    node *node2 = new node();
    node *node3 = new node();
    node *node4 = new node();
    node *node5 = new node();

    node1->value = 5;
    node2->value = 10;
    node3->value = 3;
    node4->value = 1;
    node5->value = 4;   

    node *binary_tree = NULL;

    insert_node(&binary_tree, node1);
    insert_node(&binary_tree, node2);
    insert_node(&binary_tree, node3);
    insert_node(&binary_tree, node4);
    insert_node(&binary_tree, node5);

    assert(binary_tree != NULL);
    inorder_print(binary_tree);

    return 0;
}

我有一个非常简单的程序,我想创建一个二叉树并打印它。然而,下面显示的代码段不会改变树结构。

        node *itr = *root;
        while(1)
        {
            if(itr->value > new_node->value)
                itr = itr->left;
            else
                itr = itr->right;
            if(!itr)
            {
                itr = new_node;
                break;
            }
        }

inorder_print 函数总是打印 '5'

问题是使用“itr”变量。我真的不明白如何在不使用局部变量或更改指向根的指针的情况下做到这一点。

4

2 回答 2

1

您的插入例程只会将一个节点插入根。

        if(!itr)
        {
            itr = new_node;
            break;
        }

由于itr是局部变量,new_node实际上并没有被插入。itr您可以通过创建一个指向像根这样的指针的指针来纠正这个问题。

    node **itr = root;
    while(1)
    {
        if((*itr)->value > new_node->value)
            itr = &(*itr)->left;
        else
            itr = &(*itr)->right;
        if(!*itr)
        {
            *itr = new_node;
            break;
        }
    }
于 2012-07-08T07:43:46.410 回答
1

使用 std::set。您的代码似乎是旧的 C 代码。成为 C++:

#include <set>
#include <iostream>

int main()
{
    std::set<int> binary_tree;
    binary_tree.insert(5);
    binary_tree.insert(10);
    binary_tree.insert(3);
    binary_tree.insert(1);
    binary_tree.insert(4);   

    //inorder_print(binary_tree);
    for (std::set<int> i = binary_tree.begin(); i != binary_tree.end(); ++i)
        std::cout << *i  << std::endl;
}
于 2012-07-08T11:09:51.640 回答