今天上课讲完二叉树的第一节之后,回到宿舍就把二叉树的第一道题做了。如有错误,请务必指正。
题目如下:
分析一下题目,就是用递归建立一个二叉树,在按照先序遍历输出。这里我采用的方法是每次读入两个数据,当第一个数据是字母,若第二个数据是‘(’,说明这个根有左支和右支,若第二个数据是‘,’或‘)’,说明这个节点无子支,是个叶节点。而当第一个数据是‘,’时就再读入一个数据,这个新数据若是‘)’,那么这个节点就为叶节点,若为‘(’就为根。如下:
根据这个判定,A(B(C,D),E)可化为以下的二叉树(字母上方为判断的数据):
而先序遍历输出时,就是先输出根节点的值,再输出左支和右支的值,构成递归。
以下是我的实现:
#include <stdio.h> #include <stdlib.h> struct binaryTree { char data; struct binaryTree *left; struct binaryTree *right; }; void run (); struct binaryTree *createNewBinaryTree (); void preOrderPrintBinaryTree (struct binaryTree *head); int main() { run (); return 0; } struct binaryTree *createNewBinaryTree () { char s1,s2; struct binaryTree *cur; s1=getchar (); s2=getchar (); cur=(struct binaryTree*)malloc(sizeof(struct binaryTree)); cur->left=NULL; cur->right=NULL; if (s1==',') { cur->data=s2; s1=getchar (); if (s1=='(') { cur->left=createNewBinaryTree (); cur->right=createNewBinaryTree (); } } else { cur->data=s1; if (s2=='(') { cur->left=createNewBinaryTree (); cur->right=createNewBinaryTree (); } } return cur; } void run () { struct binaryTree *head; head=createNewBinaryTree (); preOrderPrintBinaryTree (head); } void preOrderPrintBinaryTree (struct binaryTree *head) { printf ("%c",head->data); if (head->left) { preOrderPrintBinaryTree (head->left); } if (head->right) { preOrderPrintBinaryTree (head->right); } }
下面是各函数的注释:
struct binaryTree *createNewBinaryTree ()//创建二叉树 { char s1,s2; struct binaryTree *cur; s1=getchar ();//取得一数据 s2=getchar ();//取得二数据 cur=(struct binaryTree*)malloc(sizeof(struct binaryTree));//申请节点,并初始化 cur->left=NULL; cur->right=NULL; if (s1==',')//第二种情况 { cur->data=s2; s1=getchar ();获取新数据 if (s1=='(') { cur->left=createNewBinaryTree ();//左支递归 cur->right=createNewBinaryTree ();//右支递归 } } else//第一种情况 { cur->data=s1; if (s2=='(') { cur->left=createNewBinaryTree ();左支递归 cur->right=createNewBinaryTree ();右支递归 } } return cur;返回当前节点地址,以便递归 }
void preOrderPrintBinaryTree (struct binaryTree *head) { printf ("%c",head->data);//先输出节点值 if (head->left)//若左支不空 { preOrderPrintBinaryTree (head->left);//就输出左支数据,构成递归 } if (head->right)//同上 { preOrderPrintBinaryTree (head->right); } }这就是我这道题的做法,希望给大家带来启发。