Acwing 2022-10-16

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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值