zoukankan      html  css  js  c++  java
  • 求一棵树的面积,2014百度开发测试笔试题

    树的面积=最长层结点个数*树的高,要求:只能用一个函数:

    #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
  • 相关阅读:
    CSS的学习
    nodejs
    eureka注册中心
    netty的机制
    分布式事务
    spring cloud的基础
    一个发散动画的菜单控件(主要记录控件x,y坐标的运动状况)
    关于ViewPager高度自适应(随着pager页的高度改变Viewpager的高度)
    ViewPager的使用总结
    Android实现沉浸式状态栏(必须高逼格)
  • 原文地址:https://www.cnblogs.com/yihua/p/3386746.html
Copyright © 2011-2022 走看看