宽度优先搜索:树的层遍历

/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
     int maxDepth(TreeNode* root) {
        // write code here
        if (!root)
            return 0;
        queue<TreeNode* > q;//定义一个双端队列
        q.push(root);//将根结点存进去
        int deep = 0;
        while (!q.empty()) {
            ++deep;
            int num = q.size();//队列的大小,方便进行判断
            for (int i = 1; i <=num; ++i) {
                TreeNode* p = q.front();//开头元素
                q.pop();//出队列
                if (p->left)
                    q.push(p->left);
                if (p->right)
                    q.push(p->right);
            }
        }
        return deep;
     }
};