二叉树:C++实现
Posted Action and Think
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树:C++实现相关的知识,希望对你有一定的参考价值。
1#ifndef _二叉树_H
2#define _二叉树_H
3#include<iostream>
4#include<queue>
5template<class T> class BinaryTree;
6template<class T>
7class TreeNode
8{
9public:
10 TreeNode()
11 {
12 leftChild=NULL;
13 rightChild = NULL;
14 }
15 T data;
16 TreeNode<T> *leftChild;
17 TreeNode<T> *rightChild;
18};
19template<class T>
20class BinaryTree
21{
22public:
23 //二叉树进行的操作
24 void InOrder();
25 void InOrder(TreeNode<T>* currentNode);
26 void PreOrder();
27 void PreOrder(TreeNode<T>* currentNode);
28 void PostOrder();
29 void PostOrder(TreeNode<T>* currentNode);
30 void LevelOrder();
31 void Visit(TreeNode<T>* currentNode);
32public:
33 TreeNode<T> *root;
34};
35template<class T>
36void BinaryTree<T>::LevelOrder()//层序遍历
37{
38 std::queue<TreeNode<T>*> q;
39 TreeNode<T>* currentNode = root;
40 while(currentNode)
41 {
42 Visit(currentNode);
43 if(currentNode->leftChild) q.push(currentNode->leftChild);
44 if(currentNode->rightChild) q.push(currentNode->rightChild);
45 if(q.empty()) return ;
46 currentNode = q.front();
47 q.pop();
48 }
49}
50template<class T>
51void BinaryTree<T>::Visit(TreeNode<T>* currentNode)
52{
53 std::cout << currentNode->data;
54}
55template<class T>
56void BinaryTree<T>::InOrder()//中序遍历
57{
58 InOrder(root);
59}
60template<class T>
61void BinaryTree<T>::InOrder(TreeNode<T>* currentNode)
62{
63 if(currentNode)
64 {
65 InOrder(currentNode->leftChild);
66 Visit(currentNode);//显示当前节点
67 InOrder(currentNode->rightChild);
68 }
69}
70template<class T>
71void BinaryTree<T>::PreOrder()//前序遍历
72{
73 PreOrder(root);
74}
75template<class T>
76void BinaryTree<T>::PreOrder(TreeNode<T>* currentNode)
77{
78 if(currentNode)
79 {
80 Visit(currentNode);
81 PreOrder(currentNode->leftChild);
82 PreOrder(currentNode->rightChild);
83 }
84}
85template<class T>
86void BinaryTree<T>::PostOrder()//后序遍历
87{
88 PostOrder(root);
89}
90template<class T>
91void BinaryTree<T>::PostOrder(TreeNode<T>* currentNode)
92{
93 if(currentNode)
94 {
95 PostOrder(currentNode->leftChild);
96 PostOrder(currentNode->rightChild);
97 Visit(currentNode);
98 }
99}
100#endif
二叉树
1#include<iostream>
2#include"二叉树.h"
3using namespace std;
4int main()
5{
6 BinaryTree<char> tree;
7 TreeNode<char> 加,减,乘,除,a,b,c,d,e;
8 加.data = '+';
9 减.data = '-';
10 乘.data ='*';
11 除.data='/';
12 a.data = 'A';
13 b.data = 'B';
14 c.data = 'C';
15 d.data = 'D';
16 e.data = 'E';
17 tree.root = &加;
18 加.leftChild = &减;
19 加.rightChild = &e;
20 减.leftChild = &乘;
21 减.rightChild = &d;
22 乘.leftChild = &除;
23 乘.rightChild = &c;
24 除.leftChild = &a;
25 除.rightChild = &b;
26 cout<<"中序遍历:"<<endl;
27 tree.InOrder();
28 cout << endl;
29 cout<<"前序遍历:"<<endl;
30 tree.PreOrder();
31 cout << endl;
32 cout<<"后序遍历:"<<endl;
33 tree.PostOrder();
34 cout << endl;
35 cout<<"层序遍历:"<<endl;
36 tree.LevelOrder();
37 return 0;
38}
以上是关于二叉树:C++实现的主要内容,如果未能解决你的问题,请参考以下文章