用c語言把二元樹轉成中序

建立二元搜尋樹 由鍵盤上輸入數值 依序將資料鍵入該樹 第一筆資料為root 比樹根小往左子樹插入 比樹根大往右子樹插入 輸入完成後將該樹的結果以中序表示法顯示出來

1 個解答

評分
  • 3M
    Lv 6
    7 年前
    最佳解答

    #include <stdio.h>#include <stdlib.h>typedef struct node { int data ; struct node *left ; struct node *right;} Node;void insertNode(Node *node , int value){ if (value<node->data) {if (node->left==NULL) {Node *newNode;newNode = (Node *)malloc(sizeof(Node));node->left = newNode ;newNode->data = value ;}else {insertNode(node->left,value);} } else if (value>node->data) {if (node->right==NULL) {Node *newNode;newNode = (Node *)malloc(sizeof(Node));node->right = newNode ;newNode->data = value ;}else {insertNode(node->right,value);} } return ;}void infix(Node *node){ if (node==NULL)return ; infix(node->left); printf("%d ",node->data); infix(node->right);}int main (int argc, const char * argv[]) { Node *root ; root = (Node *)malloc(sizeof(Node)); printf("Please input the root value:"); scanf("%d",&(root->data)); while (1) {int tmp ;printf("Please input the child value (0 will terminate):");scanf("%d",&tmp);if ( !tmp )break;else {insertNode(root,tmp);} } infix(root); return 0;}

還有問題?馬上發問,尋求解答。