树的基础知识 二叉树

树是一种数据结构,由结点(node)和边(edge)构成。

如果一棵树具有一个名为“根”(root)的特殊节点,那么这棵树称作为有根树(rooted tree)。

有根树的节点之间具有父子关系,根是唯一一个没有父节点的节点,我们将没有子节点的节点称为外部结点(external node)或叶结点(leaf),初叶结点以外的结点称为内部结点(internal node)。

结点x的子结点数称为x的度(degree),从根到结点x的路径长度称为x的深度(depth),结点x到叶结点的最大路径长度为结点x的高(height)。

二叉树

如果一棵树拥有一个根节点,且所有结点的子结点数都不超过2,那么这棵树称为有根二叉树。

树的遍历方式(均为递归算法)

1.按照根结点,左子树,右子树的顺序输出结点编号,这称为树的前序遍历(Preorder Tree Walk)

2.按照左子树,根结点,右子树的顺序输出结点编号,这称为树的中序遍历(Inorder Tree Walk)

3.按照左子树,右子树,根结点的顺序输出结点编号,这称为树的后序遍历(Postorder Tree Walk)

洛谷P1087FBI树

这个题目是要求输出一个完全二叉树的后序遍历数组,我用了一个适应于这个题目的反向建树

位运算符<<    1<<n表示2的n次方

#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <stdio.h>
#include <cmath>
#include <string.h>
#include <vector>
char tree[1<<11];
int n;
#define ll long long
using namespace std;
char pd(char a,char b)
{
    if(a==b)
    return a;
    else
    return 'F';
}
void postParse(int u)
{
    if(u>=1<<(n+1))return ;
    postParse(2*u);
    postParse(2*u+1);
    cout<<tree[u];
}
int main()
{
    freopen("C:\\Users\\16599\\Desktop\\in.txt","r",stdin);
    cin>>n;
    //cout<<(1<<n)<<" "<<((1<<(n+1))-1)<<endl;
    for(int i=1<<n;i<=((1<<(n+1))-1);i++)
    {
        char str;
        cin>>str;
        //cout<<str<<" ";
        if(str=='0')
        tree[i]='B';
        else
        tree[i]='I';
    }
    for(int i=(1<<n)-1;i>=1;i--)
    tree[i]=pd(tree[i*2],tree[i*2+1]);
    //for(int i=1;i<1<<(n+1);i++)
    //cout<<tree[i];
    postParse(1);
    return 0;
}

 

转载于:https://www.cnblogs.com/zlhdbk/p/11271342.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值