二叉树的先序遍历 (Ver. I)

题目描述

按先序遍历给出一棵二叉树,每个结点都有一个水平位置:左子结点在它左边一个单位,右子结点在右边1个单位。从左向右输出每个水平位置的所有节点的权值之和。

例如:以下二叉树有三个水平位置,从左至右的输出是7,11,3。

输入

测试数据有多组,每组测试数据输入按先序遍历输入一棵二叉树,其中-1代表空节点(一棵树的节点数量不超过 103

当输入的二叉树是一棵空树时,结束输入。

输出

对于每组测试数据,首先输出一行"Case x:",其中x代表这是第x个测试数据的输出,然后从左到右输出每个水平位置所有节点的权值之和

样例输入

5 7 -1 6 -1 -1 3 -1 -1 8 2 9 -1 -1 6 5 -1 -1 12 -1 -1 3 7 -1 -1 -1 -1

样例输出

Case 1: 7 11 3 Case 2: 9 7 21 15

提示

 
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int M[100];
int x[100];
int I=0;
class BiTreeNode
{
public:
    int data;
    int x;
    BiTreeNode *Left;
    BiTreeNode *Right;
    BiTreeNode()
    {
        Left=NULL;
        Right=NULL;
    }
    ~BiTreeNode()
    {
        delete Left;
        delete Right;
    }
};
 
class BiTree
{
public:
    BiTreeNode *Root;
    BiTree()
    {
        Root=CreateBiTree(-1,0);
    }
    BiTreeNode *CreateBiTree(int n,int d)
    {
        BiTreeNode *T;
        int p;
        if(n==-1)
            cin>>p;
        else
            p=n;
        if(p==-1)
            return NULL;
        else
        {
            T=new BiTreeNode();
            T->data=p;
            T->x=d;
            T->Left=CreateBiTree(-1,d-1);
            T->Right=CreateBiTree(-1,d+1);
        }
        return T;
    }
    void Pre(BiTreeNode *p)
    {
        if(p)
        {
            M[I]=p->data;
            x[I]=p->x;
            I++;
            Pre(p->Left);
            Pre(p->Right);
        }
    }
};
 
int main()
{
    int T=1;
    while(T)
    {
        for(int i=0;i<I;i++)
        {
            M[i]=0;
            x[i]=0;
        }
        I=0;
        BiTree Tree;
        if(Tree.Root==NULL)
            break;
        Tree.Pre(Tree.Root);
        for(int i=0;i<I;i++)
        {
            for(int j=0;j<I-1-i;j++)
            {
                if(x[j]>x[j+1])
                {
                    swap(x[j],x[j+1]);
                    swap(M[j],M[j+1]);
                }
            }
        }
        for(int i=0;i<I;i++)
        {
            for(int j=i+1;j<I;j++)
            {
                if(x[j]==x[i])
                {
                    M[i]+=M[j];
                    x[j]=-9999;
                    M[j]=0;
                }
            }
        }
        cout<<"Case "<<T<<":"<<endl;
        for(int i=0;i<I;i++)
            if(x[i]!=-9999)
                cout<<M[i]<<" ";
        cout<<endl;
        cout<<endl;
        T++;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/SZU-DS-wys/p/12180818.html