首页 > 编程语言 > 详细

二叉树(c++实现)

时间:2021-08-11 09:28:00      阅读:21      评论:0      收藏:0      [点我收藏+]

1. 链表表示法

 1 #include<iostream>
 2 using namespace std;
 3 
 4 struct Node
 5 {
 6     int val;
 7     Node* left;
 8     Node* right;
 9     Node(int v)
10     {
11         val=v;
12         left=NULL;
13         right=NULL;
14     }
15 };
16 
17 
18 int main()
19 {
20     Node* root=new Node(1); // 1号结点下面初始为空
21     root->left=new Node(2);
22     root->right=new Node(3);
23     root->left->left=new Node(4); // 4号结点下面两个为空
24     return 0;
25 }

 

2. 数组实现法

 1 #include<iostream>
 2 #include<string>
 3 #include<cstring>
 4 #include<vector>
 5 
 6 using namespace std;
 7 
 8 char tree[10]; //初始时全部为空
 9 
10 int root(char key)
11 {
12     if(tree[0]!=\0)
13     {
14         cout<<"tree already had root";
15     }
16     else
17         tree[0]=key;
18     return 0;
19 }
20 
21 int setLeft(char key,int parent) // parent is the index of array
22 {
23     if(tree[parent]==\0)
24     {
25         cout<<"can‘t set child at "<<(parent*2+1)<<" no parent found"<<endl;
26     }
27     else
28     {
29         tree[parent*2+1]=key;
30     }
31     return 0;
32 }
33 
34 int setRight(char key,int parent)
35 {
36     if(tree[parent]==\0)
37     {
38         cout<<"can‘t set child at "<<(parent*2+2)<<" no parent found"<<endl;
39     }
40     else
41     {
42         tree[parent*2+2]=key;
43     }
44     return 0;
45 }
46 
47 int print()
48 {
49     for(int i=0;i<10;i++)
50     {
51         if(tree[i]!=\0)
52         {
53             cout<<tree[i]<<endl;
54         }
55         else
56             cout<<"-"<<endl;
57     }
58     return 0;
59 }
60 
61 
62 
63 int main()
64 {
65     root(A);
66     setRight(C, 0);
67     setLeft(D, 1);
68     setRight(E, 1);
69     setRight(F, 2);
70     print();
71     return 0;
72 }

 

二叉树(c++实现)

原文:https://www.cnblogs.com/cwfeng/p/15126419.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!