#include
#include
typedef struct tree {
char val;
struct tree * leftChild;
struct tree * rightChild;
struct tree * parent;
}Tree,*CTree;
int flag=0;
void Init(CTree &root){
root->val = ' ';
root->leftChild = NULL;
root->rightChild = NULL;
}
CTree CreateNode(char ch ){
CTree node = (CTree)malloc(sizeof(Tree));
node->val = ch;
node->leftChild = NULL;
node->rightChild = NULL;
return node;
}
void CreateTree(CTree& root){
char ch;
printf("请输入字符:");
scanf("%c" , &ch);
getchar();
if(ch == '#')
{
return ;
}
root = CreateNode(ch);
CreateTree(root->leftChild);
CreateTree(root->rightChild);
}
void PreOrder(CTree root) {
if (root == NULL) {
return;
}
printf("%c",root->val);
PreOrder(root->leftChild);
PreOrder(root->rightChild);
}
void InOrder(CTree root) {
if (root == NULL) {
return;
}
InOrder(root->leftChild);
printf("%c",root->val);
InOrder(root->rightChild);
}
void FindF_lrchilld(CTree root){
if(root){
if(root->val == 'F'){
if(root->leftChild && root->rightChild)
printf("F的左右孩子分别是:%c,%c\n",root->leftChild->val,root->rightChild->val);
else if(root->leftChild && !root->rightChild)
printf("F的左孩子为%c,右孩子为NULL\n",root->leftChild->val);
else if(root->rightChild && !root->leftChild)
printf("F的右孩子为%c,左孩子为NULL\n",root->rightChild->val);
else
printf("F没有左右孩子\n");
flag = 1;
return;
}
if(flag == 1)
return;
FindF_lrchilld(root->leftChild);
FindF_lrchilld(root->rightChild);
}
}
int Depth(CTree root){
if(!root)
return 0;
int m,n;
m = Depth(root->leftChild);
n = Depth(root->rightChild);
if (m > n)
return m+1;
else
return n+1;
}
int LeafCount(CTree root){
if (!root)
return 0;
if(root->leftChild == NULL && root->rightChild == NULL )
return 1;
else
return LeafCount(root->leftChild) + LeafCount(root->rightChild);
}
int Node_one_Count(CTree T){
if(T==NULL) {
return 0;
}
if(T->leftChild==NULL&&T->rightChild!=NULL||T->rightChild==NULL&&T->leftChild!=NULL){
return 1+Node_one_Count(T->leftChild)+Node_one_Count(T->rightChild);
}
return Node_one_Count(T->leftChild)+Node_one_Count(T->rightChild);
}
int main(){
CTree root = (CTree)malloc(sizeof(Tree));
Init(root);
CreateTree(root);
printf("先序遍历的结果为:");
PreOrder(root); //先序
printf("\n");
printf("中序遍历的结果为:");
InOrder(root); //中序
printf("\n");
printf("F孩子的左右节点:");
FindF_lrchilld(root);
printf("\n");
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)