所以我写了这个小小的和平代码作为自己的练习......
但是我在*traverse_inorder(p->left)* 内存访问冲突和程序崩溃行进入 travers_inorder 函数。为什么???有任何想法吗?
更新:我正在使用 Visual Studio 2008 SP1 一个 Visual C++ 编译器
#include <iostream>
#include <time.h>
using namespace std;
struct tree_node
{
tree_node *left;
tree_node *right;
int value;
};
void populate_rnd_tree(tree_node *root, int cnt);
void traverse_inorder(tree_node *p);
int main()
{
srand(time(NULL));
tree_node * nTmp = new tree_node;
populate_rnd_tree(nTmp, 10);
traverse_inorder(nTmp);
return 1;
}
void populate_rnd_tree(tree_node *root, int cnt)
{
tree_node *old = root, *left, *right;
left = new tree_node;
right = new tree_node;
int val = 0;
// exit condition
if (cnt == 0) return;
val = rand()%50;
old->value = val;
old->left = left;
old->right = right;
populate_rnd_tree(left, cnt-1);
populate_rnd_tree(right, cnt-1);
return;
}
void traverse_inorder(tree_node *p)
{
if (p != NULL)
{
traverse_inorder(p->left);
cout << p->value << endl;
traverse_inorder(p->right);
}
}