[英]Binary Tree Search Implementation and function declaration c++
How do I declare the tree_search function in the main ? 如何在main中声明tree_search函数? I have tried to do it but i keep getting some weird results.
我曾尝试这样做,但我一直得到一些奇怪的结果。 What I want to do is search for node
0,11
in the binary tree and display it if it was found. 我想做的是在二叉树中搜索节点
0,11
并显示它(如果找到)。 Please Help :D 请帮助: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;
}
Output 产量
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
The reason you're getting the weird characters is that you're outputting a pointer to a data structure. 之所以会出现奇怪的字符,是因为您正在输出指向数据结构的指针。 It prints the memory address of it then.
然后打印它的内存地址。
Instead of: 代替:
std::cout << r << std::endl;
consider using: 考虑使用:
std::cout << r->value << std::endl;
although note that for the second case you need to wrap the expression with an "if (r)" so that the program doesn't crash due to accessing a NULL pointer. 尽管请注意,在第二种情况下,您需要使用“ if(r)”包装表达式,以使程序不会由于访问NULL指针而崩溃。
You can also define an operator that allows printing pointers to the data structure directly. 您还可以定义一个运算符,该运算符允许直接将指针打印到数据结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.