二叉树cpp的实现

 1 #include <iostream>
 2 #include <stack>
 3 #include <queue>
 4 using namespace std;
 5 
 6 typedef int ElemType;
 7 typedef struct BiTNode{
 8     ElemType data;
 9     struct BiTNode * left;
10     struct BiTNode * right;
11     BiTNode(ElemType data){
12         this->data = data;
13         this->left = NULL;
14         this->right = NULL;
15     }
16 }BiTNode, *BitTree ;
17 
18 void InOrder(BitTree tree){
19     if(tree!=NULL){
20         InOrder(tree->left);
21         cout<<tree->data<< " ";
22         InOrder(tree->right);
23     }
24 }
25 
26 void LevelOredr(BitTree tree){
27     queue<BitTree> TreeQueue;
28     TreeQueue.push(tree);
29     while(!TreeQueue.empty()){
30         BitTree node = TreeQueue.front();
31         cout<<node->data<< " ";
32         TreeQueue.pop();
33         if(node->left)
34             TreeQueue.push(node->left);
35         if(node->right)
36             TreeQueue.push(node->right);
37     }
38     cout<<"\n";
39 }
40 void PreOrder(BitTree tree){
41     stack<BitTree> TreeStack;
42     while(tree||!TreeStack.empty()){
43         if(tree){//向左走
44             cout<<tree->data<< " ";
45             TreeStack.push(tree);
46             tree = tree->left;
47         }else{
48             tree = TreeStack.top()->right;
49             TreeStack.pop();
50         }
51     }
52     cout<<"\n";
53 }
54 
55 BitTree CreateBitTree(ElemType data){
56     return new BiTNode(data);
57 }
58 int main()
59 {
60     BitTree tree = CreateBitTree(10);
61     tree->left = CreateBitTree(15);
62     tree->right = CreateBitTree(20);
63     tree->right->left = CreateBitTree(66);
64     PreOrder(tree);
65     LevelOredr(tree);
66     InOrder(tree);
67     return 0;
68 }

 

posted @ 2020-04-06 20:37  wkfxm  阅读(303)  评论(0编辑  收藏  举报