二叉查找树的正确打开方式

//C++语言与JAVA语言最大的区别之一,在于JAVA拥有完善的内存回收机制,而C++不完善,甚至可以说没有。

//这就要就C++程序员手动的回收内存空间,避免内存泄漏。本程序举了一个有关二叉树的创建和销毁的小栗子。

//

// BinaryTree.cpp : 定义控制台应用程序的入口点。




#include "stdafx.h"
#include <iostream>

using namespace std;

struct biTree{
int data;
biTree *lchild;
biTree *rchild;
};
static biTree *root = nullptr;
biTree * createBitree(biTree *p, biTree *source){

if (p==nullptr)
{
p = source;
return p;
}
else{

if (p->data > source->data){

p->lchild = createBitree((p->lchild), source);
return p;
}
else{
p->rchild=createBitree((p->rchild), source);
return p;
}
}

}
biTree * DelbiTree(biTree *root){

if (root == nullptr){

return  root;//无左孩子或者右孩子
}
else{
biTree *src = root;
root->lchild = DelbiTree(root->lchild);
root->rchild = DelbiTree(root->rchild);
root->data = 0;
delete root;//当心,不要重复删除
root = nullptr;
src = nullptr;
return nullptr;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int arr[] = {4,5,2,1,6,8,3,9,7};
int length = sizeof(arr)/sizeof(int);

biTree *head = nullptr;
biTree *now = nullptr;

for (int i = 0; i < length; i++)
{
now = new biTree();
now->lchild = nullptr;
now->rchild = nullptr;
now->data = arr[i];
head = now;
root = createBitree(root,head);

}

        now  = nullptr;
head = nullptr;

root = DelbiTree(root);
getchar();


return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值