Acwing1259 二叉树的遍历
题目的要求:根据二叉树的中序遍历和层次遍历求解二叉树的先序遍历
我们基本的求解思路:1.根据二叉树的中序遍历和层次遍历构建二叉树,然后再写出二叉树的先序遍历,但是我们需要注意的问题是如何才能判断是否为叶子结点?
我们可以使用一个child指针来指示第一个可能是其子节点的元素在层次遍历中的位置,判断叶子节点还是根节点一共有两种方式:
1. 若分析该节点时,child指针越界了,说明该节点必然为叶子节点
2. 若child指针没有越界,但是该节点在中序遍历的相邻左右节点均被遍历过了,或者一边被遍历过,另一边为空,那么此时该节点为叶子节点
//二叉树的遍历,根据二叉树的中序遍历和层次遍历求解二叉树的先序遍历
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
typedef struct node {
char data;
node *left,*right;
}node;
char in[30],level[30];
//构建二叉树
node* build(int l1,int r1,int l2,int r2) {
if(l1 > r1) return nullptr;
int i,j;
for(int i = l2;i <= r2;i++) {
bool flag = true;
for(int j = l1;j <= r1;j++) {
if(level[i] == in[j]) {
flag = false;
break;
}
}
if(!flag) break;
}
node* root = (node*)malloc(sizeof(node));
root->data = level[i];
root->left = build(l1,j-1,l2,r2);
root->right = build(j+1,r1,l2,r2);
return root;
}
//先序遍历
void pre(node* root) {
if(root == nullptr) return;
cout<<root->data;
pre(root->left);
pre(root->right);
}
int main() {
int m = 0,n = 0;
cin>>in;//中序输入
cin>>level;//层次输入
m = strlen(in);
n = strlen(level);
node *root = build(0,m-1,0,n-1);
pre(root);
return 0;
}
Acwing 3432 二叉树
这道题目的基本要求是求解满二叉树的最近的公共祖先,我们使用满二叉树的一个性质,也就是说对于2个结点,子节点数/2向下取整,就可以得到父节点,我们将层数更深的结点不断地使用这一个操作,直至两个结点的层数相同,这个即为二者的最近的公共祖先。
//求解满二叉树的任意2个结点的最近的公共祖先
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main() {
int x,y;
while(true) {
cin>>x>>y;
if(x > y) x = x / 2;
else if(x < y) y = y / 2;
else break;
}
printf("%d\n",x);
return 0;
}