机试指南 cha 3 二叉树
已知前序和中序求后序遍历
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <stack>
#include <math.h>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stack>
using namespace std;
char s1[100],s2[100];
// 前序中序求后序代码
typedef struct BiNode
{
struct BiNode *lchild,*rchild;
char data;
}BiNode,*BiTree;
void postOrder(BiTree t)
{
if (t)
{
postOrder(t->lchild);
postOrder(t->rchild);
cout << t->data;
}
}
BiTree buildTree(int b1,int e1,int b2,int e2)
{
// 对 b1 - e1前序 和 b2 - e2中序进行操作
// 每次仅能判断一个根节点,然后递归判断
BiTree root = (BiTree)malloc(sizeof(BiNode));
root->lchild = NULL;
root->rchild = NULL;
root->data = s1[b1];
int rootIndex;
for (int i = b2;i<=e2;i++)
{ // 找到中序遍历中根节点的位置
if (s2[i] == s1[b1])
{
rootIndex = i;
break;
}
}
if (rootIndex != b2)
{
// 左子树不为空
root->lchild = buildTree(b1+1,b1+rootIndex-b2,b2,rootIndex-1);
}
if (rootIndex != e2)
{
// 右子树不为空
root->rchild = buildTree(b1+rootIndex-b2+1,e1,rootIndex+1,e2);
}
return root;
}
int main()
{
while (cin >> s1 >> s2)
{
int len1 = strlen(s1); // 从开始地址到\0符号为止的长度
int len2 = strlen(s2);
BiTree t = buildTree(0,len1-1,0,len2-1);
postOrder(t);
cout << endl;
}
return 0;
}
二叉树
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <stack>
#include <math.h>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stack>
using namespace std;
// 二叉树 完全二叉树 用顺序存储好一些
int count1(int m,int n,int &sum)
{
if ( m <= n)
{
sum ++;
count1(2*m,n,sum);
}
if (m+1 <= n )
{
sum ++;
count1(2*m+1,n,sum);
}
return sum;
}
int main()
{
int m,n;
while (scanf("%d %d",&m,&n)!=EOF)
{
int sum = 1;
cout << count1(2*m,n,sum)<< endl;
}
return 0;
}
树查找
在顺序存储单元中查找某层元素,通过完全二叉树的两条性质,找到本层的第一个数和最后一个数打印输出即可。
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <stack>
#include <math.h>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stack>
using namespace std;
const int N = 1000;
int main()
{
int tree[N], n, d;
while (scanf("%d", &n) != EOF)
{
for (int i = 0; i < n; i++)
{
scanf("%d", &tree[i]);
}
scanf("%d", &d);
int start = (int)pow(2, d - 1); // 此层第一个数
if (start > n)
{
printf("EMPTY\n");
}
else
{
int end = pow(2, d) - 1 > n ? n : (int)pow(2, d) - 1;
for (int i = start - 1; i < end - 1; i++)
{
printf("%d ", tree[i]);
}
printf("%d\n", tree[end - 1]);
}
}
return 0;
}