要點:二叉樹遍歷,要針對基本圖形的遍歷,先序(NLR),中序(LNR),後序(LRN),且往上看,它是某節點的左子,但往下看,它可能仍是某節點的根,這時就要繼續往下找,直到找到沒有子(也就是葉子)時,左子,纔是真正的左子,本身體會。node
圖形:spa
程序:code
#include<stdio.h> #include<stdlib.h> struct node{ char data; struct node* left; struct node* right; }; struct node* newNode(char data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data=data; node->left=NULL; node->right=NULL; return node; } void printPostorder(struct node* node){ if(node == NULL) return; printPostorder(node->left); printPostorder(node->right); printf("%c ",node->data); } void printInorder(struct node* node){ if(node==NULL){ return; } printInorder(node->left); printf("%c ",node->data); printInorder(node->right); } void printPreorder(struct node* node){ if(node==NULL){ return; } printf("%c ",node->data); printPreorder(node->left); printPreorder(node->right); } int main(){ struct node *root=newNode('A'); root->left=newNode('B'); root->right=newNode('C'); root->left->left=newNode('D'); root->right->left=newNode('F'); root->right->right=newNode('H'); root->left->left->right=newNode('E'); root->right->right->left=newNode('I'); root->right->right->left->right=newNode('G'); printf("\nPreorder raversal of binary tree is \n"); printPreorder(root); printf("\nInorder raversal of binary tree is \n"); printInorder(root); printf("\nPostorder raversal of binary tree is \n"); printPostorder(root); return 0; }
輸出:blog
Preorder raversal of binary tree is A B D E C F H I G Inorder raversal of binary tree is D E B A F C I G H Postorder raversal of binary tree is E D B F G I H C A