[Leetcode]107. Binary Tree Level Order Traversal II

用队列实现树的广度优先搜索

题目如下:


示例

实现代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
const vector> vvt;
class Solution {
public:
    vector> levelOrderBottom(TreeNode* root) {
      vector> vvt;
        if(root == NULL) return vvt;
        queue q;
        q.push(root);
        while(!q.empty()){
            int size = q.size();
            vector level;
            for(int i = 0; i < size; i++){
                TreeNode* node = q.front();
                level.push_back(node->val);
                if( node->left != NULL ) q.push(node->left);
                if( node->right != NULL ) q.push(node->right);
                q.pop();
            }
            vvt.push_back(level);
        }
        reverse(vvt.begin(),vvt.end());
        return vvt;
    }
};

以前一直写的深度优先,感觉这个还是蛮新鲜的,作为c++萌新,也学了一些c++中queue的函数
注:
queue中:pop()函数无返回值,front()才有
vector> vvt类似于Java中的ArrayList,
插入用push_back()
颠倒用reverse(vvt.begin(),vvt.end())

你可能感兴趣的:([Leetcode]107. Binary Tree Level Order Traversal II)