C++建立查找删除节点二叉排序树

来源:互联网 发布:未来计价软件视频 编辑:程序博客网 时间:2024/05/20 12:50

简历方法。二叉树简历。只是小的在根的左边 大的在右边。。

删除 是只写了左右子树都不为空的删除 

删掉当前节点。用一个数据来填补空缺。代码里面看


H

#ifndef H_H#define H_H#include <iostream>struct Node{int num;Node*lNext;Node*rNext;};class BinaryTree{public:BinaryTree();~BinaryTree();void Insert(Node*&p, int m);void show(Node*&p);Node*Find(int m);void Delete(int m);Node*pHead;};#endif //H_H

CPP

#include "h.h"using namespace std;BinaryTree::BinaryTree(){}BinaryTree::~BinaryTree(){}void BinaryTree::Insert(Node*&p, int m){if (m < 0)return;if (p == nullptr){p = new Node;p->num = m;p->lNext = nullptr;p->rNext = nullptr;return;}if (m == p->num)return;if (m < p->num)Insert(p->lNext, m);else if (m>p->num)Insert(p->rNext, m);}void BinaryTree::show(Node*&p){if (p){cout << p->num << endl;show(p->lNext);show(p->rNext);}}Node*BinaryTree::Find(int m){Node*p = pHead;while (p){if (p->num == m)return p;if (p->num<m){p = p->rNext;}else{p = p->lNext;}}return nullptr;}void BinaryTree::Delete(int m){Node*p = Find(m);if (!p){return;}if (p->lNext&&p->rNext)//先拿个左子树。再一直倒右拐。直到没有右子树了。这个就是拿来替换删掉那个节点的节点了{Node*temp = p->lNext;Node *d = p;while (temp->rNext){d = temp;temp = temp->rNext;}p->num = temp->num;if (d!=p)//这个表明。是倒右拐了的 前驱指向下一个的下一个{Node*t = d->rNext;d->rNext = temp->lNext;delete t;//处理被过掉那个节点 这个t delete了指向的内存才能重用t = nullptr;}else//没有右子树 直接接左边{Node*t = d->lNext;d->lNext = temp->lNext;delete t;t = nullptr;//cout << "temp is " << temp->num << endl;}}}int main(){BinaryTree bt;//bt.initTree();bt.Insert(bt.pHead, 100);bt.Insert(bt.pHead, 90);bt.Insert(bt.pHead, 110);bt.Insert(bt.pHead, 80);bt.Insert(bt.pHead, 70);bt.Insert(bt.pHead, 65);bt.Insert(bt.pHead, 75);bt.Insert(bt.pHead, 95);bt.show(bt.pHead);Node*p = bt.Find(80);if (p){cout << p->num << " had been found"<<endl << endl;}else{cout << "Not Find" << endl;}bt.Delete(90);试过90 100 都阔以bt.show(bt.pHead);system("pause");}
他是你拿后面的节点来填你换的节点这个套路。看图理解理解



0 0
原创粉丝点击