NOJ-建立二叉樹的二叉連結串列儲存結構-西工大資料結構
阿新 • • 發佈:2019-01-31
今天上課講完二叉樹的第一節之後,回到宿舍就把二叉樹的第一道題做了。如有錯誤,請務必指正。
題目如下:
分析一下題目,就是用遞迴建立一個二叉樹,在按照先序遍歷輸出。這裡我採用的方法是每次讀入兩個資料,當第一個資料是字母,若第二個資料是‘(’,說明這個根有左支和右支,若第二個資料是‘,’或‘)’,說明這個節點無子支,是個葉節點。而當第一個資料是‘,’時就再讀入一個數據,這個新資料若是‘)’,那麼這個節點就為葉節點,若為‘(’就為根。如下:
根據這個判定,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);
}
}
這就是我這道題的做法,希望給大家帶來啟發。