Sicily 1156. Binary tree

本文介绍了一种利用数组模拟完全二叉树并进行前序遍历的方法。通过构建包含节点内容及其左右子树节点的数组,文章提供了一个C++实现示例,展示了如何确定根节点并进行递归前序遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

完全二叉树的前序遍历,但用不着真的构建一个完全二叉树,可以使用数组来进行模拟。具体就是构建一个1000的数组,每个位置包含有节点内容、左子树节点、右子树节点即可,然后找出根节点,再使用递归进行前序遍历。

Run Time: 0sec

Run Memory: 324KB

Code length: 923Bytes

SubmitTime: 2012-01-04 17:02:20

// Problem#: 1156
// Submission#: 1172813
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <iostream>
#include <cstring>
using namespace std;

struct Node {
    char content;
    int left, right;
};

Node node[ 1001 ];
bool exist[ 1001 ];
bool root[ 1001 ];

void preorder( int n ) {
    if ( n != 0 ) {
        cout << node[ n ].content;
        preorder( node[ n ].left );
        preorder( node[ n ].right );
    }
}

int main()
{
    int n, i;

    while ( cin >> n ) {
        memset( exist, false, sizeof( exist ) );
        memset( root, true, sizeof( root ) );
        while ( n-- ) {
            cin >> i;
            cin >> node[ i ].content >> node[ i ].left >> node[ i ].right;
            exist[ i ] = true;
            root[ node[ i ].left ] = false;
            root[ node[ i ].right ] = false;
        }

        for ( i = 1; i <= 1000; i++ ) {
            if ( exist[ i ] && root[ i ] )
                break;
        }
        preorder( i );
        cout << endl;
    }

    return 0;

}                                 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值