二叉树搜索实现和函数声明c ++

时间:2015-03-20 15:39:07

标签: c++ function binary-tree binary-search-tree declaration

如何在main中声明tree_search函数?我试过这样做,但我一直得到一些奇怪的结果。我想要做的是在二叉树中搜索节点0,11并在找到它时显示它。请帮助:D

#include <iostream>

class BinTreeNode {
public:
    BinTreeNode(int value) {
        this->value = value;
        this->left = NULL;
        this->right = NULL;
    }
    int value;
    int target;
    BinTreeNode* left;
    BinTreeNode* right;
};

BinTreeNode* tree_insert(BinTreeNode* tree, int item) {
    if (tree == NULL)
        tree = new BinTreeNode(item);
    else if (item < tree->value)
        if (tree->left == NULL)
            tree->left = new BinTreeNode(item);
        else
            tree_insert(tree->left, item);
    else if (tree->right == NULL)
        tree->right = new BinTreeNode(item);
    else
        tree_insert(tree->right, item);
    return tree;
}

void postorder(BinTreeNode* tree) {
    if (tree->left != NULL)
        postorder(tree->left);
    if (tree->right != NULL)
        postorder(tree->right);
    std::cout << tree->value << std::endl;
}

void in_order(BinTreeNode* tree) {
    if (tree->left != NULL)
        in_order(tree->left);
    std::cout << tree->value << std::endl;
    if (tree->right != NULL)
        in_order(tree->right);
}

BinTreeNode* tree_search(BinTreeNode* tree, int target) {
    BinTreeNode* r = tree;
    while (r != NULL) {
        if (target == r->value)
            std::cout << r << std::endl;
        else if (target > r->value)
            r = r->left;

        else
            r = r->right;
        std::cout << r << std::endl;
    }
}

int main(int argc, char* argv[]) {
    BinTreeNode* t = tree_insert(0, 6);
    tree_insert(t, 10);
    tree_insert(t, 5);
    tree_insert(t, 2);
    tree_insert(t, 3);
    tree_insert(t, 4);
    tree_insert(t, 11);

    in_order(t);
    tree_search(t, 11);

    return 0;
}

输出

2
4
5
6
10
11
0x6c6f28   //at the moment im getting these weird characters and i want it to 
0x6c6f40   // display the (0,11) node if it was found
0

1 个答案:

答案 0 :(得分:1)

您获得奇怪字符的原因是您正在输出指向数据结构的指针。然后打印出它的内存地址。

而不是:

std::cout << r << std::endl;

考虑使用:

std::cout << r->value << std::endl;

虽然请注意,对于第二种情况,您需要使用“if(r)”包装表达式,以便程序不会因访问NULL指针而崩溃。

您还可以定义一个允许直接打印指向数据结构的指针的运算符。