C语言搜索二叉树测试代码
作者:互联网
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <stdbool.h> 4 5 typedef int DATA; 6 typedef struct _SNode_ 7 { 8 DATA data; 9 struct _SNode_ *p_Right, *p_Left; 10 }SNode; 11 12 SNode *CreateTree(const DATA d) 13 { 14 SNode *m_root = (SNode *)malloc(sizeof(SNode)); 15 m_root->data = d; 16 m_root->p_Left = m_root->p_Right = NULL; 17 return m_root; 18 } 19 20 void InsertRight(SNode *p, const DATA d) 21 { 22 SNode *pNew = CreateTree(d); 23 p->p_Right = pNew; 24 } 25 26 void InsertLeft(SNode *p, const DATA d) 27 { 28 SNode *pNew = CreateTree(d); 29 p->p_Left = pNew; 30 } 31 32 void PreOrder(SNode *p) 33 { 34 printf("%d ", p->data); 35 if (p->p_Left) 36 PreOrder(p->p_Left); 37 if (p->p_Right) 38 PreOrder(p->p_Right); 39 } 40 41 void InOrder(SNode *p) 42 { 43 if (p->p_Left) 44 InOrder(p->p_Left); 45 printf("%d ", p->data); 46 if (p->p_Right) 47 InOrder(p->p_Right); 48 } 49 50 void PostOrder(SNode *p) 51 { 52 if (p->p_Left) 53 PostOrder(p->p_Left); 54 if (p->p_Right) 55 PostOrder(p->p_Right); 56 printf("%d ", p->data); 57 } 58 59 bool LookUp(SNode *p, const DATA d) 60 { 61 while (p) 62 { 63 if (p->data == d) 64 return true; 65 else if (p->data > d) 66 p = p->p_Left; 67 else 68 p = p->p_Right; 69 } 70 return false; 71 } 72 73 // 方式二:使用二级指针 74 void SetAt(SNode *p, const DATA d) // 创建搜索二叉树 75 { 76 if (p == NULL) 77 { 78 p = CreateTree(d); 79 return; 80 } 81 SNode **ppRoot = &p; 82 while (*ppRoot) 83 { 84 if ((*ppRoot)->data < d) 85 ppRoot = &(*ppRoot)->p_Right; 86 else if ((*ppRoot)->data > d) 87 ppRoot = &(*ppRoot)->p_Left; 88 } 89 SNode *pNew = CreateTree(d); 90 *ppRoot = pNew; 91 } 92 93 int main() 94 { 95 SNode *pRoot = CreateTree(30); 96 SetAt(pRoot, 75); 97 SetAt(pRoot, 20); 98 SetAt(pRoot, 40); 99 SetAt(pRoot, 10); 100 SetAt(pRoot, 60); 101 SetAt(pRoot, 50); 102 103 if (LookUp(pRoot, 52)) 104 printf("找到了!\n"); 105 else 106 printf("没有找到!\n"); 107 108 InOrder(pRoot); 109 110 return 0; 111 }
标签:Right,pRoot,SNode,C语言,二叉树,测试代码,data,ppRoot,Left 来源: https://www.cnblogs.com/veis/p/12579390.html