c璇█ 浜屽弶鏍戠殑鍒涘缓鍙婂叾閫掑綊涓庨潪閫掑綊绠楁硶
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c璇█ 浜屽弶鏍戠殑鍒涘缓鍙婂叾閫掑綊涓庨潪閫掑綊绠楁硶相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/nbsp' title='nbsp'>nbsp
style class oid tree 闈為€掑綊 else 缁撴灉 malloc浠ヤ笅鍖呭惈鏈夊墠鍚庡簭鐨勯€掑綊鍜岄潪閫掑綊绠楁硶
#include<stdio.h> #include<stdlib.h> #define MAXSIZE 20 typedef struct node{ int data; struct node* right; struct node* left; }Node; typedef struct{ Node *root; }Tree; void insert(Tree *tree,int value) { Node *node=(Node *)malloc(sizeof(Node)); node->data=value; node->left=NULL; node->right=NULL; if(tree->root==NULL) tree->root=node; else { Node *temp=tree->root; while(temp!=NULL) { if(value<temp->data) { if(temp->left==NULL) { temp->left=node; break; } else temp=temp->left; } else { if(value>temp->data) { if(temp->right==NULL) { temp->right=node; break; } else temp=temp->right; } } } } } //閫掑綊鍓嶅簭閬嶅巻娉? void Preorder(Node *node) { if(node!=NULL) { printf("%d ",node->data); Preorder(node->left); Preorder(node->right); } } //閫掑綊鍚庡簭閬嶅巻娉? void Postorder(Node *node) { if(node!=NULL) { Postorder(node->left); Postorder(node->right); printf("%d ",node->data); } } //闈為€掑綊鍓嶅簭閬嶅巻鏂规硶 void PreorderNonrecurion(Node *node) { if(node!=NULL) { Node *stack[MAXSIZE]; int top=-1; Node *p=NULL; stack[++top]=node; while(top!=-1) { p=stack[top--]; printf("%d ",p->data); if(p->right!=NULL) stack[++top]=p->right; if(p->left!=NULL) stack[++top]=p->left; } } } //闈為€掑綊鍚庡簭閬嶅巻娉?/span> void PostorderNonrecurion(Node *node) { if(node!=NULL) { Node *stack1[MAXSIZE];int top1=-1; Node *stack2[MAXSIZE];int top2=-1; stack1[++top1]=node; Node *p=NULL; while(top1!=-1) { p=stack1[top1--]; stack2[++top2]=p; if(p->left!=NULL) stack1[++top1]=p->left; if(p->right!=NULL) stack1[++top1]=p->right; } Node *q=NULL; while(top2!=-1) { q=stack2[top2--]; printf("%d ",q->data); } } } int main(){ int arr[7]={6,3,4,2,5,1,7}; Tree tree; tree.root=NULL; for(int i=0;i<7;i++) insert(&tree,arr[i]); printf("閫掑綊鍓嶅簭閬嶅巻缁撴灉涓篭t"); Preorder(tree.root); printf(" "); printf("閫掑綊鍚庡簭閬嶅巻缁撴灉涓篭t"); Postorder(tree.root); printf(" "); printf("闈為€掑綊鍓嶅簭閬嶅巻缁撴灉涓篭t"); PreorderNonrecurion(tree.root); printf(" "); printf("闈為€掑綊鍚庡簭閬嶅巻缁撴灉涓篭t"); PostorderNonrecurion(tree.root); }
以上是关于c璇█ 浜屽弶鏍戠殑鍒涘缓鍙婂叾閫掑綊涓庨潪閫掑綊绠楁硶的主要内容,如果未能解决你的问题,请参考以下文章
涓€涓父瑙佺殑鏍℃嫑闈㈣瘯棰橈細浜屽弶鏍戠殑搴忓垪鍖栧拰鍙嶅簭鍒楀寲
[LeetCode] 255. Verify Preorder Sequence in Binary Search Tree 楠岃瘉浜屽弶鎼滅储鏍戠殑鍏堝簭搴忓垪