#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <algorithm>
#include <stack>
#include <queue>
#define N 1000000
using namespace std;
char s[55], pre[101], mid[101], post[101];
int n;
struct node
{
char data;
node *l, *r;
};
node *buildtree(char *mid, char *post, int len)//已知后序中序求先序
{
if(!len)
return NULL;
node *root = new node;
root -> data = post[len - 1];
int i;
for(i = 0; i < len; i++)
{
if(post[len - 1] == mid[i])
break;
}
root -> l = buildtree(mid, post, i);
root -> r = buildtree(mid + i + 1, post + i, len - i - 1);
return root;
}
node *buildtree(char *pre, char *mid, int len)// 已知先序中序求后序 (用指针加速)
{
if(!len)
return NULL;
node *root = new node;
root -> data = pre[0];
int i;
for(i = 0; i < len; i++)
{
if(pre[0] == mid[i])
break;
}
root -> l = buildtree(pre + 1, mid, i);
root -> r = buildtree(pre + i + 1, mid + i + 1, len - i - 1);
return root;
}
node *buildtree()//建立二叉树
{
node *root;
if(s[n] == ',') //递归边界
{
root = NULL;
n++;
}
else
{
root = new node;
root -> data = s[n++];
root -> l = buildtree();
root -> r = buildtree();
}
return root;
}
void midorder(node *root)
{
if(root != NULL)
{
midorder(root -> l);
printf("%c", root -> data);
midorder(root -> r);
}
}
void postorder(node *root)
{
if(root != NULL)
{
postorder(root -> l);
postorder(root -> r);
printf("%c", root -> data);
}
}
void preorder(node *root)
{
if(root != NULL)
{
printf("%c", root -> data);
preorder(root -> l);
preorder(root -> r);
}
}
queue <node *> q; // 层序遍历用队列实现的
void level(node *root)
{
if(root != NULL)
q.push(root);
while(!q.empty())
{
if(q.front() -> l != NULL)
q.push(q.front() -> l);
if(q.front() -> r != NULL)
q.push(q.front() -> r);
printf("%c", q.front() -> data);
q.pop();
}
printf("\n");
}
int stair(node* t)//深度
{
if(t == NULL)
{
return 0;
}
if(t -> l == NULL && t -> r == NULL)
{
return 1;
}
if(stair(t -> l) > stair(t -> r))
{
return stair(t -> l) + 1;
}
else
{
return stair(t -> r) + 1;
}
}
int leave(node *root)//叶子节点的个数
{
if(root == NULL)
return 0;
if(root -> l == NULL && root -> r = NULL)
return 1;
else
return leave(root -> l) + leave(root -> r);
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%s %s", mid, post);
node *root = new node;
root -> l = NULL;
root -> r = NULL;
root = buildtree(mid, post, strlen(mid));
preorder(root);
printf("\n");
}
return 0;
}
二叉树最简单的建树和三序之间的关系加层序遍历+深度+叶子节点的个数
最新推荐文章于 2022-08-01 13:45:15 发布