• 树的基础知识 二叉树


    树是一种数据结构,由结点(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;
    }
  • 相关阅读:
    包 (package)
    Object类
    异常
    接口
    抽象类
    多态(经典案例)
    三大特性:(经典代码)
    对象创建的过程(重点理解)
    final关键字
    cocos2dx工程中接入支付宝sdk
  • 原文地址:https://www.cnblogs.com/zlhdbk/p/11271342.html
Copyright © 2020-2023  润新知