使用递归遍与历释放二叉数

来源:互联网 发布:windows编程视频教程 编辑:程序博客网 时间:2024/06/07 22:54
// 使用递归遍与历释放二叉数#include "stdafx.h"#include <stdio.h>#include <stdlib.h>struct Node{int data;Node *pLeft;Node *pRight;};void InsertTree(Node *&pRoot,int data){if(pRoot == NULL){pRoot=(Node *)malloc(sizeof(Node));pRoot->data=data;pRoot->pLeft=pRoot->pRight=NULL;return;}if(pRoot->data<data)InsertTree(pRoot->pRight,data);elseInsertTree(pRoot->pLeft,data);}void PrintTree(const Node *pRoot){if(pRoot == NULL)return;PrintTree(pRoot->pLeft);printf("node:%d\n",pRoot->data);PrintTree(pRoot->pRight);}void FreeTree(Node *pRoot){if(pRoot == NULL)return;FreeTree(pRoot->pLeft);FreeTree(pRoot->pRight);printf("free:%d\n",pRoot->data);free(pRoot);}int main(){Node *pRoot=NULL;InsertTree(pRoot,5);InsertTree(pRoot,8);InsertTree(pRoot,3);InsertTree(pRoot,4);InsertTree(pRoot,2);PrintTree(pRoot);FreeTree(pRoot);return 0;}


 

原创粉丝点击