实现由双亲节点存储的树转化为二叉树的遍历算法实现

都知道,树的先根遍历和后根遍历分别对应了二叉树的先序遍历和中序遍历,而由先序遍历和中序遍历可以确定唯一的二叉树。#include#include#includeusing namespace std;vectorpre;//保存先序遍历结果vectorpost;//保存后序遍历结果int bitree[100];//保存二叉树列表形式结果int n;int first_
摘要由CSDN通过智能技术生成


都知道,树的先根遍历和后根遍历分别对应了二叉树的先序遍历和中序遍历,而由先序遍历和中序遍历可以确定唯一的二叉树。


#include<iostream>
#include<bits/stdc++.h>
#include<vector>
using namespace std;
vector<int>pre;//保存先序遍历结果
vector<int>post;//保存后序遍历结果
int bitree[100];//保存二叉树列表形式结果
int n;
int first_son(int t,int * pa){
//    得到树的第一个孩子
    for (int i = 0;i<n;i++){
        if(pa[i] == t)return i;
    }
    return -2;
}
int next_sib(int t,int * pa){
//    得到树的孩子的下一个兄弟
    for(int i = t+1;i<n;i++){
        if(pa[i] == pa[t])return i;
    }
    return -2;
}
void pre_root(int t,int *pa){
//    先根遍历
    pre.push_back(t);
    for(int x = first_son(t,pa);x!=-2;x = next_sib(x,pa)){

        pre_root(x,pa);
    }

}
void post_root(int t,int * pa){
//    后根遍历
     for(int x = first_son(t,pa);x!=-2;x = next_sib(x,pa)){
    
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值