求一棵樹的面積,2014百度開發測試筆試題

樹的面積=最長層結點個數*樹的高,要求:只能用一個函數:node

#include<iostream>
#include<queue>

using namespace std;

struct Node{
    int val;
    Node *lchild;
    Node *rchild;
} ;

//建立二叉樹
Node *CreateTree(){
    char lflag='n',rflag='n';
    Node*root=new Node;
    root->lchild=NULL;
    root->rchild=NULL;

    cout<<"請輸入結點的值:"<<endl;
    cin>>root->val;
    
    cout<<"結點"<<root->val<<"是否有左子樹?請輸入Y or N:";
    cin>>lflag;
    if(lflag=='y'||lflag=='Y')root->lchild=CreateTree();
    else root->lchild =NULL;

    cout<<"結點"<<root->val<<"是否有右子樹?請輸入Y or N:";
    cin>>rflag;
    if(rflag=='y'||rflag=='Y')root->rchild=CreateTree();
    else root->rchild =NULL;

    return root;
}

//求樹的積
int GetArea(Node *root){
    int high=-1;    //樹高
    int width=0;    //當前層樹寬    
    int maxwidth=0; //樹的最大寬度

    queue<Node*> nodes;    //用隊列來存儲上一層樹的結點
    Node *pnode;        //指向隊列中的某個結點
    
    nodes.push(root);
    while(!nodes.empty()){
        width=0;
        high++;
        //開始遍歷同一層結點
        for(int i=nodes.size();i>0;i--){
            pnode=nodes.front();
            nodes.pop();
            if(pnode->lchild!=NULL){
                nodes.push(pnode->lchild);
                width++;}
            if(pnode->rchild!=NULL){
                nodes.push(pnode->rchild);
                width++;
            }
        }
        if(width>maxwidth)maxwidth=width;
    }

    return high*maxwidth;
}

void main(){
    Node*root;
    root=CreateTree();
    cout<<GetArea(root);
}
View Code
相關文章
相關標籤/搜索