您的位置:首页 > 其它

二叉树相关问题

2013-02-26 20:04 239 查看
复习下二叉树,创建二叉树,分别以先序,中序,后续三种遍历访问二叉树,输出二叉树的叶子节点及叶子节点的个数,并输出二叉树的高度

[cpp]

#include<iostream>

#include<cstdio>

#include<cstring>

#include<cstdlib>

using namespace std;

typedef struct BiTNode

{

char data;

struct BiTNode *lchild,*rchild;

}BiTNode,*BiTree;

int Max(int x,int y)

{

return x>y?x:y;

}

void Create(BiTree &T) //先序建一颗二叉树

{

char ch;

scanf("%c",&ch);

if(ch=='#')

T=NULL;

else

{

T=(BiTNode *)malloc(sizeof(BiTNode));

T->data=ch;

Create(T->lchild);

Create(T->rchild);

}

}

void Preorder(BiTree &root) //先序遍历打印二叉树

{

if(root!=NULL)

{

printf("%c ",root->data);

Preorder(root->lchild);

Preorder(root->rchild);

}

}

void Inorder(BiTree &root) //中序遍历打印二叉树

{

if(root!=NULL)

{

Inorder(root->lchild);

printf("%c ",root->data);

Inorder(root->rchild);

}

}

void Postorder(BiTree &root) //后续遍历打印二叉树

{

if(root!=NULL)

{

Postorder(root->lchild);

Postorder(root->rchild);

printf("%c ",root->data);

}

}

void Preorderleaf(BiTree &root) //先序遍历输出叶子节点

{

if(root!=NULL)

{

if(root->lchild==NULL&&root->rchild==NULL)

printf("%c ",root->data);

Preorderleaf(root->lchild);

Preorderleaf(root->rchild);

}

}

int LeafCount(BiTree &root) //统计叶子节点的个数

{

int leaf;

if(root==NULL)

leaf=0;

else if(root->lchild==NULL&&root->rchild==NULL)

leaf=1;

else

leaf=LeafCount(root->lchild)+LeafCount(root->rchild);

return leaf;

}

int PostTreeDepth(BiTree &root) //统计树的高度

{

int hl,hr,max;

if(root!=NULL)

{

hl=PostTreeDepth(root->lchild);

hr=PostTreeDepth(root->rchild);

max=Max(hl,hr);

return max+1;

}

else

return 0;

}

void dowork()

{

BiTree cam;

Create(cam);

Preorder(cam);

printf("\n");

Inorder(cam);

printf("\n");

Postorder(cam);

printf("\n");

printf("叶子节点:");

Preorderleaf(cam);

printf("\n");

printf("叶子节点的个数为:%d\n",LeafCount(cam));

printf("树的深度为:%d\n",PostTreeDepth(cam));

}

int main()

{

dowork();

return 0;

}

二叉树的常见问题有如下几个,如果解决好了,就跟链表一样轻松:唯一不一样的是,二叉树是非线性结构。常见的问题如下:

二叉树的问题

1.二叉树三种周游(traversal)方式:

[cpp] view plaincopy

1 二叉树的问题

2 1.二叉树三种周游(traversal)方式:
3 2.怎样从顶部开始逐层打印二叉树结点数据

4 3.如何判断一棵二叉树是否是平衡二叉树
5 4.设计一个算法,找出二叉树上任意两个节点的最近共同父结点,复杂度如果是O(n2)则不得

6
7 分。

8 5.如何不用递归实现二叉树的前序/后序/中序遍历?
9 6.在二叉树中找出和为某一值的所有路径

10 7.怎样编写一个程序,把一个有序整数数组放到二叉树中?
11 8.判断整数序列是不是二叉搜索树的后序遍历结果

12 9.求二叉树的镜像
13 10.一棵排序二叉树(即二叉搜索树BST),令 f=(最大值+最小值)/2,设计一个算法,找出距

14
15 离f值最近、大于f值的结点。复杂度如果是O(n2)则不得分。

16 11.把二叉搜索树转变成排序的双向链表
17 12.打印二叉树中的所有路径(与题目5很相似)

3.如何判断一棵二叉树是否是平衡二叉树

4.设计一个算法,找出二叉树上任意两个节点的最近共同父结点,复杂度如果是O(n2)则不得分。

5.如何不用递归实现二叉树的前序/后序/中序遍历?

6.在二叉树中找出和为某一值的所有路径(注意是到叶子节点)

7.怎样编写一个程序,把一个有序整数数组放到二叉树中?

8.判断整数序列是不是二叉搜索树的后序遍历结果

9.求二叉树的镜像

10.一棵排序二叉树(即二叉搜索树BST),令 f=(最大值+最小值)/2,设计一个算法,找出距离f值最近、大于f值的结点。复杂度如果是O(n2)则不得分。

11.把二叉搜索树转变成排序的双向链表

12.打印二叉树中的所有路径(与题目6很相似)解决思路:

1.二叉树三种周游(traversal)方式:任何一本数据结构的书都有描述,略过;

2.怎样从顶部开始逐层打印二叉树结点数据?

设置一个队列,然后只要队列不为空,将对首元素的左右孩子加入队列(如果左右孩子不为空),然后将队列的首元素出对即可,如下图所示:

二叉树如下图所示:

那么,整个过程如下:

自然,就输出了a,b,c,d,e,f

3.如何判断一个二叉树是否是平衡的?

太简单了,利用递归就可以了:判断根节点的左右子树深度之差是否小于等于1(这里需要用到求深度的方法),如果是,根节点就是平衡的;然后,在判断根节点的左孩子和右孩子是否是平衡的。如此继续下去,直到遇见叶子节点。一旦不是,立刻返回false;

计一个算法,找出二叉树上任意两个节点的最近共同父结点,复杂度如果是O(n2)则不得分

首先找到这两个点key1和key2,并且记录下找到这两个点的路径Path1和Path2。然后,找到第一个点k满足,key1<k<key2就可以了。

如图:

假设key1 = 5,key2 = 7,那么显然,Path1{8,6,5}, Path2{8,6,7}。满足第一个key1<k<key2的k为6。故k = 6。

至于怎么求出Path1和Path2,可以看问题12。

5.如何不用递归实现二叉树的前序/后序/中序遍历?(网易面试就问到了,悲剧了,当时一下子卡住了)

看看书,基本任何一本数据结构的书都有,主要利用栈。

6.在二叉树中找出和为某一值的所有路径?

还是先解决12题目,访问二叉树到叶子节点的任意路径。这个问题解决了,自然求和看是否满足条件就可以了。

7.怎样编写一个程序,把一个有序整数数组放到二叉树中?

递归,还是利用递归:

设有int array[begin,end],首先将array[(begin + end)/2]加入二叉树,然后递归去做array[begin,(begin + end)/2 - 1]和array[(begin + end)/2 + 1, end]。注意写好函数的形式就可以了。一切都很自然。

8.判断整数序列是不是二叉搜索树的后序遍历结果?

看看吧,后续遍历是这样做的:左右根,所以访问的最有一个节点实际上就是整棵二叉树的根节点root:然后,找到第一个大于该节点值的根节点b,b就是root右子树最左边的节点(大于根节点的最小节点)。那么b前面的就是root的左子树。既然是二叉搜索树的遍历结果,那么在b和root之间的遍历结果,都应该大于b。去拿这个作为判断的条件。

9.求二叉树的镜像?

还是利用递归:只要节点不为空,交换左右子树的指针,然后在分别求左子树的镜像,再求右子树的镜像,直到节点为NULL。

10.一棵排序二叉树(即二叉搜索树BST),令 f=(最大值+最小值)/2,设计一个算法,找出距离f值最近、大于f值的结点。复杂度如果是O(n2)则不得分。

首先,在BST中,最小值就是最左边的节点,最大值就是最右边的节点。

在分别求出min和max后,求出f。然后利用查找,找出一个大于f的节点就可以了。

复杂度为logN。

11.把二叉搜索树转变成排序的双向链表

12..打印二叉树中的所有路径

路径的定义就是从根节点到叶子节点的点的集合。

还是利用递归:用一个list来保存经过的节点,如果已经是叶子节点了,那么打印list的所有内容;如果不是,那么将节点加入list,然后继续递归调用该函数,只不过,入口的参数变成了该节点的左子树和右子树。

程序如下:

[cpp] view plaincopy

18 解答1:自己看书了

19 解答2:
20 //问题2:怎样从顶部开始逐层打印二叉树结点数据

21 void PrintAtLevel(BiTNode* root){
22 vector<BiTNode*> vector;

23 vector.push_back(root);
24 while(!vector.empty()){

25 BiTNode* tmp = vector.front();
26 if(tmp->lchild != NULL)

27 vector.push_back(tmp->lchild);
28 if (tmp->rchild != NULL)

29 vector.push_back(tmp->rchild);
30 cout << tmp->data << endl;

31 vector.pop_back();
32 }

33 }
34 //问题3:如何判断一棵二叉树是否是平衡二叉树

35 int isBalencedTree(treeNode* root){
36 if (root == NULL)

37 return 0;
38 int depth1 = getDepth(root->lchild);

39 int depth2 = getDepth(root->rchild);
40 if (depth1 == depth2 || depth1 == depth2 + 1 || depth1 == depth2 - 1)

41 return 1;
42 else

43 return 0;
44 int flag1 = isBalencedTree(root->lchild);

45 int flag2 = isBalencedTree(root->rchild);
46 if (flag1 && flag2)

47 return 1;
48 else

49 return 0;
50 }

51 //问题4:设计一个算法,找出二叉树上任意两个节点的最近共同父结点,复杂度如果是O(n2)
52

53 则不得分。
54 int getPublicAncestors(treeNode* root,int key1,int key2){

55 treeNode* ptr = root;
56 int path1[1000];

57 int pathLen1 = 0;
58 while (ptr != NULL){

59 if (key1 == ptr->data){
60 path1[pathLen1] = ptr->data;

61 pathLen1 ++;
62 printArray(path1,pathLen1);

63 break;
64 }

65 else
66 if (ptr->data > key1){

67 path1[pathLen1] = ptr->data;
68 pathLen1 ++;

69 ptr = ptr->lchild;
70 }

71 else
72 if (ptr->data < key1){

73 path1[pathLen1] = ptr->data;
74 pathLen1 ++;

75 ptr = ptr->rchild;
76 }

77 }
78 ptr = root;

79 int path2[1000];
80 int pathLen2 = 0;

81 while (ptr != NULL){
82 if (key2 == ptr->data){

83 path2[pathLen2] = ptr->data;
84 pathLen2 ++;

85 printArray(path2,pathLen2);
86 break;

87 }
88 else

89 if (ptr->data > key2){
90 path2[pathLen2] = ptr->data;

91 pathLen2 ++;
92 ptr = ptr->lchild;

93 }
94 else

95 if (ptr->data < key2){
96 path2[pathLen2] = ptr->data;

97 pathLen2 ++;
98 ptr = ptr->rchild;

99 }
100 }

101 int i = pathLen1 - 1;
102 //key1和key2有序,

103 if (key2 < key1){
104 key2 = key2^key1;

105 key1 = key2^key1;
106 key2 = key2^key1;

107 }
108 for (; i > 0; i --){

109 if (key1 < path1[i] && path1[i]< key2){
110 int result = path1[i];

111 return result;
112 }

113 }
114 }

115 //问题6:在二叉树中找出和为某一值的所有路径
116 void FindPath(treeNode* root, int path[],int pathLen,int expectedSum, int

117
118 currentSum){

119 if (root == NULL)
120 return;

121 currentSum += root->data;
122 path[pathLen] = root->data;

123 pathLen ++;
124 if (currentSum == expectedSum && root->lchild == NULL && root->rchild ==

125
126 NULL){

127 printArray(path,pathLen);
128 }

129 if (root->lchild != NULL){
130 FindPath(root->lchild,path,pathLen,expectedSum,currentSum);

131 }
132 if (root->rchild != NULL){

133 FindPath(root-
134

135 >rchild,path,pathLen,expectedSum,currentSum);
136 }

137 currentSum -= root->data;
138 }

139
140 //问题7:怎样编写一个程序,把一个有序整数数组放到二叉树中?

141 void createTreeFromArray(int a[], int begin, int end, treeNode** root){
142 if (begin > end)

143 return;
144 else{

145 *root = (treeNode*) malloc(sizeof(treeNode));
146 int mid = (begin + end) / 2;

147 (*root)->data = a[mid];
148 (*root)->rchild = NULL;

149 (*root)->lchild = NULL;
150 createTreeFromArray(a, begin ,mid - 1, &(*root)->lchild);

151 createTreeFromArray(a, mid + 1 ,end, &(*root)->rchild);
152 }

153 }
154 //问题8:判断整数序列是不是二叉搜索树的后//序遍历结果

155 int isPostTraverse(int a[], int begin ,int end){
156 if(begin >= end)

157 return 1;
158 else{

159 int root = a[end];
160 int lroot;

161 int i;
162 int location = begin;

163 for (i = begin; i < end ; i ++){
164 if(a[i] > root){

165 location = i;
166 lroot = a[i];

167 break;
168 }

169 }
170 for (i = location + 1; i < end; i++){

171 if (a[i] < lroot){
172 return 0;

173 }
174 }

175 int flag1 = isPostTraverse(a,begin,location -1);
176 int flag2 = isPostTraverse(a,location,end - 1);

177 if (flag1 && flag2)
178 return 1;

179 else
180 return 0;

181 }
182 }

183 //问题9:求二叉树的镜像
184 void changeMirror(treeNode** root){

185 if ( *root == NULL)
186 return;

187 else{
188 treeNode* temp = (*root)->lchild;

189 (*root)->lchild = (*root)->rchild;
190 (*root)->rchild = temp;

191 changeMirror(&(*root)->lchild);
192 changeMirror(&(*root)->rchild);

193 }
194 }

195 //问题10:10.一棵排序二叉树(即二叉搜索树BST),令 f=(最大值+最小值)/2,设计一个算
196

197 //法,找出距离f值最近、大于f值的结点。复杂度如果是O(n2)则不得分。
198 int findNearMid(treeNode** root){

199 treeNode* ptr = *root;
200 int min, max;

201 while (ptr != NULL){
202 min = ptr->data;

203 ptr = ptr->lchild;
204 }

205 printf("the min is %d\n",min);
206 ptr = *root;

207 while (ptr != NULL){
208 max = ptr->data;

209 ptr = ptr->rchild;
210 }

211 printf("the max is %d\n",max);
212 int half = (min + max) >> 1;

213 printf("half is %d\n",half);
214 ptr = *root;

215 while (1){
216 if (ptr->data < half){

217 ptr = ptr->rchild;
218 }

219 else
220 if (ptr->data > half){

221 int result = ptr->data;
222 return result;

223 }
224 else

225 {
226 return (ptr->rchild)->data;

227 }
228 }

229 }
230 //问题12:打印二叉树中的所有路径(与题目5很相似)

231 void printPathsRecur(treeNode* node, int path[], int pathLen) {
232 if (node == NULL)

233 return;
234 // append this node to the path array

235 path[pathLen] = node->data;
236 pathLen++;

237 // it's a leaf, so print the path that led to here
238 if (node->lchild == NULL && node->rchild == NULL) {

239 printArray(path, pathLen);
240 } else {

241 // otherwise try both subtrees
242 printPathsRecur(node->lchild, path, pathLen);

243 printPathsRecur(node->rchild, path, pathLen);
244 }

245 }
246

247 void printPaths(treeNode* node) {
248 int path[1000];

249 printPathsRecur(node, path, 0);
250 }

251 //用到的辅助函数:
252 /**

253 * 求二叉树的深度
254 */

255 int getDepth(tNode root) {
256 if (root == NULL)

257 return 0;
258 else

259 return getDepth(root->lchild) > getLeaf(root->rchild) ? 1 +
260

261 getDepth(
262 root->lchild) : 1 + getDepth(root->rchild);

263 // {
264 // int depthLchild = 1 + getDepth(root->lchild);

265 // int depthRchild = 1 + getDepth(root->rchild);
266 // return depthLchild > depthRchild ? depthLchild:

267
268 depthRchild;

269 // }
270 }

271 /**
272 * 打印数组

273 */
274 void printArray(int ints[], int len) {

275 int i;
276 for (i = 0; i < len; i++) {

277 printf("%d ", ints[i]);
278 }

279 printf("\n");
280 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: