C++实现链式存储二叉树
生活随笔
收集整理的這篇文章主要介紹了
C++实现链式存储二叉树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include <iostream>
using namespace std;
typedef char ElemType;typedef struct BiNode {//節點的創建ElemType data;struct BiNode *lchild, *rchild;
} BiNode, *BiTree;void PreOrderTraverse(BiTree T) {//先序遍歷if (T) {cout << T->data;PreOrderTraverse(T->lchild);PreOrderTraverse(T->rchild);}
}void InOrderTraverse(BiTree T) {//中序遍歷if (T) {InOrderTraverse(T->lchild);cout << T->data;InOrderTraverse(T->rchild);}
}void PostOrderTraverse(BiTree T) {//后序遍歷if (T) {PostOrderTraverse(T->lchild);PostOrderTraverse(T->rchild);cout << T->data;}
}void CreateBiTree(BiTree &T) {//創建二叉樹char ch;cin >> ch;if (ch == '#')T = NULL;else {T = new BiNode;T->data = ch;CreateBiTree(T->lchild);CreateBiTree(T->rchild);}
}void Copy(BiTree T, BiTree &NewT) {//復制出一個新的二叉樹if (T == NULL) {NewT = NULL;return ;} else {NewT = new BiNode;NewT->data = T->data;Copy(T->lchild, NewT->lchild);Copy(T->rchild, NewT->rchild);}
}int Depth(BiTree T) {//求深度if (T == NULL)return 0;else {int m = Depth(T->lchild);int n = Depth(T->rchild);if (m > n)return (m + 1);elsereturn (n + 1);}
}int NodeCount(BiTree T) {//求節點的個數if (T == NULL)return 0;elsereturn NodeCount(T->lchild) + NodeCount(T->rchild) + 1;
}int LeafCount(BiTree T) {//求葉子的個數if (T == NULL)return 0;if (T->lchild == NULL && T->rchild == NULL)return 1;elsereturn LeafCount(T->lchild) + LeafCount(T->rchild);
}int main() {BiTree T;//創建一顆二叉樹cout << "以先序遍歷輸入(以#結束)要存儲的元素" << endl;CreateBiTree(T);cout << "先序遍歷輸出: ";PreOrderTraverse(T);cout<<endl;cout << "中序遍歷輸出: ";InOrderTraverse(T);cout<<endl;cout << "后序遍歷輸出" ;PostOrderTraverse(T);cout<<endl;cout << "該樹的深度為: ";cout << Depth(T) << endl;cout << "該樹的節點個數為: ";cout << NodeCount(T) << endl;cout << "該樹的葉子個數為: ";cout << LeafCount(T) << endl;system("pause");return 0;
}
測試效果圖:
測試結果:
本文參考文章地址:
https://blog.csdn.net/deaidai/article/details/71834241
總結
以上是生活随笔為你收集整理的C++实现链式存储二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。