首页 > 代码库 > 广度优先搜索求树的深度

广度优先搜索求树的深度

#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);
}