C++构建二叉树

时间:2021-09-30 19:40:04
//这里构建的是二叉树不是普通树,它最多只有两个孩子。
#include<iostream>
using namespace std;
struct Binarytreenode
{
int value;
Binarytreenode* left;
Binarytreenode* right;
};
Binarytreenode* creatBinarytree(int value)
{
Binarytreenode*root=new Binarytreenode;
root->value =value;
root->left =NULL;
root->right=NULL;
return root;
}
void connectBinarytreenode(Binarytreenode*parent,Binarytreenode*right,Binarytreenode*left)
{
if(parent!=NULL)
{
parent->left =left;
parent->right =right;
}
}
void printBinarytreenode(Binarytreenode*pnode)
{
if(pnode==NULL)
cout<<"this node is NULL"<<endl;
else
{
cout<<pnode->value<<endl;
if(pnode->left==NULL)
cout<<"left  NULL"<<" ";
else
cout<<"left"<<" "<<pnode->left->value <<" ";
if(pnode->right ==NULL)
cout<<"right  NULL"<<" "<<endl;
else 
cout<<"right"<<" "<<pnode->right ->value <<endl;
}
}
//前序遍历
void printBinarytree(Binarytreenode*root)
{
printBinarytreenode(root);
if(root!=NULL)
{
if(root->left !=NULL)
printBinarytree(root->left);
if(root->right !=NULL)
printBinarytree(root->right );
}
}
void destroyBinarytree(Binarytreenode*root)
{
if(root!=NULL)
{
Binarytreenode*pleft=root->left;
Binarytreenode*pright=root->right ;
delete root;
root=NULL;
destroyBinarytree(pleft);
destroyBinarytree(pright);
}
}
int main()
{
Binarytreenode*p1=creatBinarytree(1);
Binarytreenode*p2=creatBinarytree(2);
Binarytreenode*p3=creatBinarytree(3);
Binarytreenode*p4=creatBinarytree(4);
Binarytreenode*p5=creatBinarytree(5);
Binarytreenode*p6=creatBinarytree(6);
connectBinarytreenode(p4,p3,p5);
connectBinarytreenode(p3,p1,NULL);
connectBinarytreenode(p5,p2,NULL);
printBinarytree(p4);
destroyBinarytree(p4);
return 0;
}