树转二叉树

文本中用括号表示法输入二叉树,编写程序识别输入,用父亲表示法建立树,转换成一颗二叉树。
细节部分,注释很清晰了

#include<cstdio>
#include<stack>
#include<iostream>
using namespace std;
struct node
{
    char c;//字符的值
    int key;//本节点的地址
    int father;//父节点的地址
}tree[100];
struct node2
{
    char c;
    int child;
    int brother;
    node2()
    {
        child = -1;
        brother = -1;
    }
}tree2[100];
void build_tree(char *c,node *tree)
{
    stack<int> k;
    tree[0].c = c[0];
    tree[0].key = 0;
    tree[0].father = -1;//树的首节点初始化
    int temp = 0;//当前最大的节点的地址
    for (int i = 1; i < strlen(c); i++)//处理指令
    {
        //遇到'('则将当前最大的数组下标(父节点的地址)入栈
        if (c[i] == '(') k.push(tree[temp].key);
        //遇到‘)’则将栈顶元素出栈
        else if (c[i] == ')') k.pop();
        //当不是括号时,对树赋值
        else
        {
            temp++;//指针加一
            tree[temp].c = c[i];
            tree[temp].father = k.top();
            tree[temp].key = temp;
        }
    }
}
void change(node *tree, int num, node2 *tree2)//树的转换
{
    for (int i = 0; i < num; i++)//每个节点的位置不变,写入第一个兄弟节点,以及孩子节点即可
    {
        tree2[i].c = tree[i].c;
        if (tree2[tree[i].father].child == -1)
            tree2[tree[i].father].child = i;//写入每个节点的孩子节点
        for (int j = i + 1; j < num; j++)
        {
            if (tree[j].father == tree[i].father)
            {
                tree2[i].brother = j;//写入兄弟节点
                break;
            }
        }
    }
}

int main(){
    FILE *p;
    p = fopen("input.txt", "r");
    char c[100];
    fgets(c, 100, p);
    build_tree(c, tree);
    change(tree, 8, tree2);
    for (int i = 0; i < 7; i++){
        printf("%d %d\n", tree2[i].brother, tree2[i].child);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值