重点是理解其思想,其中还有不少可以改进的问题,例如增加节点的形式,还有new的内存的没有释放等等. 源码如下
#include<iostream>
using namespace std;
struct Tree
{
struct Tree* lnode;
struct Tree* rnode;
int data;
};
void insertnode(struct Tree* &root, int b)
{
if (root == NULL)
{
root = new struct Tree;
root->data = b;
root->lnode = NULL;
root->rnode = NULL;
}
else
{
if (root->data > b)
{
insertnode(root->lnode, b);
}
else
{
insertnode(root->rnode, b);
}
}
}
void printLSR(struct Tree*root)
{
if (root != NULL)
{
printLSR(root->lnode);
cout << root->data << ",";
printLSR(root->rnode);
}
return;
}
void printRSL(struct Tree*root)
{
if (root != NULL)
{
printRSL(root->rnode);
cout << root->data << ",";
printRSL(root->lnode);
}
return;
}
int main()
{
struct Tree*root=NULL;
int a[5] = { 3, 4, 2, 5, 6 };
for (int i = 0; i < 5; i++)
{
insertnode(root, a[i]);
}
printLSR(root);
cout << endl<<"--------------" << endl;
printRSL(root);
system("pause");
return 0;
}
特别要注意的问题是栈上变量的声明周期问题.
|