二叉樹資料結構實現
阿新 • • 發佈:2018-11-10
#include<iostream> #include<string.h> #include<vector> #include <queue> using namespace std; struct BiNode { int val; BiNode *left; BiNode *right; BiNode(int v,BiNode *l = nullptr,BiNode *r = nullptr) { val = v; left = l; right = r; } }; //實現二叉排序樹 void Insert(BiNode* &p,int val) { if(p == nullptr) p = new BiNode(val); else if(p->val > val) Insert(p->left,val); else if (p->val < val) Insert(p->right,val); else { //相同元素的情況 } } void PreOrder(BiNode *p) { if (p != nullptr) { cout << p->val << " "; PreOrder(p->left); PreOrder(p->right); } } void InOrder(BiNode* p) { if (p != nullptr) { InOrder(p->left); cout << p->val << " "; InOrder(p->right); } } void PostOrder(BiNode *p) { if(p != nullptr) { PostOrder(p->left); PostOrder(p->right); cout << p->val << " "; } } //佇列實現層序遍歷 void LayerOrder(BiNode *p) { queue<BiNode*> bnQueue; if (p != nullptr) { bnQueue.push(p); while(!bnQueue.empty()) { BiNode* curNode = bnQueue.front(); cout << curNode->val << " "; bnQueue.pop(); if(curNode->left != nullptr) bnQueue.push(curNode->left); if(curNode->right != nullptr) bnQueue.push(curNode->right); } } } BiNode* findNode(BiNode *p,int val) { if(nullptr == p) return nullptr; if(val == p->val) return p; BiNode* curP = findNode(p->left,val); if(nullptr != curP) return curP; else return findNode(p->right,val); } BiNode* FindMinNode(BiNode* p) { if(nullptr == p) return nullptr; while(nullptr != p->left) { p = p->left; } return p; } //刪除某一個元素 bool Delete(BiNode * &p, int val) { if(nullptr == p) return false; if (val != p->val) { if(Delete(p->left,val)) return true; else return Delete(p->right,val); } else { if (nullptr == p->left && nullptr == p->right)//沒有子節點,直接刪除 { delete p; p = nullptr; } else if(nullptr != p->left && nullptr != p->right)//兩個子節點 { BiNode* minNode = FindMinNode(p->right); p->val = minNode->val; Delete(p->right,p->val); //錯誤做法, 因為minNode是新建的副本,更改無效 // if(nullptr != minNode->right) // minNode = minNode->right; } else//1個子節點 { BiNode * temp; if(nullptr != p->left) { temp = p->left; delete p;//防止記憶體洩漏 p = temp; } else { temp = p->right; delete p; p = temp; } } return true; } } int size(BiNode *p) { if(p == nullptr) return 0; else return size(p->left) + size(p->right) + 1; } int height(BiNode * p) { if(nullptr == p) return 0; else if(nullptr == p->left && nullptr == p->right) return 1; else return max(height(p->left),height(p->right)) + 1; } void Destroy(BiNode * &p)//不是引用也能銷燬,delete p是釋放指標指向的記憶體,並不是指標本身所佔有的記憶體 { if (p->left != nullptr) Destroy(p->left); if (p->right != nullptr) Destroy(p->right); if(p != nullptr) delete p; } int main() { int a[] = {5,1,2,3,4,6,7,8,9,10}; BiNode *parent = nullptr; for (int i=0;i<10;i++) { Insert(parent,a[i]); } PreOrder(parent); cout << endl; InOrder(parent); cout << endl; PostOrder(parent); cout << endl; LayerOrder(parent); cout << endl; int h = height(parent); BiNode* p9 = findNode(parent,9); Delete(parent,5); InOrder(parent); cout << endl; Destroy(parent); system("pause"); return 0; }