zoukankan      html  css  js  c++  java
  • 广度优先搜索求树的深度

    #include<iostream>
    #include<vector>
    #include<stack>
    #include<string>
    #include<queue>
    #include<algorithm>
    #include<numeric>
    using namespace std;
    
    class node{
    public:
        int val;
        node* left;
        node* right;
        node():val(0),left(NULL),right(NULL){}
    };
    
    node* createTree()
    {
        node* head = new node[14];
        for(int i = 0;i<10;i++)
        {
            head[i].val = i;
            if(2*i+1 < 10)
            head[i].left = head + 2*i + 1;
            if(2*i+2 < 10)
            head[i].right = head + 2*i + 2;
        }
        return head;
    }
    
    
    int depth(node * root)
    {
     node* temp = NULL, *head = root; ///注意对这个的理解,*一般是紧跟变量的
     int ret = 0;
     queue<node*> q;
     q.push(head);
     q.push(NULL);
     while(!q.empty())
     {
         temp = q.front();
         q.pop();
         if(NULL == temp)
         {
             ret++;
             if(q.empty())
             break;
             else
             q.push(NULL);
         }
         else{
             if(temp->left != NULL)
             q.push(temp->left); 
             if(temp->right != NULL)
             q.push(temp->right); 
         }
     }
     return ret;
    }
    
    int main()
    {
        node* t = createTree();
         cout<<depth(t);
    }
    berkeleysong
  • 相关阅读:
    k8s中文网
    python range用法
    python 日志滚动 分文件
    python 语法
    flask 中文编码解码
    python的杨辉三角
    mysql8.0.4以后修改密码方式变更
    flask学习视频
    oralce的lag和lead函数
    JNI 各类数据类型处理
  • 原文地址:https://www.cnblogs.com/berkeleysong/p/3747281.html
Copyright © 2011-2022 走看看