leetcode 102. Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]

bfs层序遍历整颗树。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        queue<TreeNode*> q;
        vector<vector<int> > ans;
        if (root == nullptr) return ans;
        q.push(root);
        while (!q.empty()) {
            vector<int> v;
            int n = q.size();
            while (n-- > 0) {
                TreeNode* u = q.front();
                q.pop();
                //cout << u->val << endl;
                v.push_back(u->val);
                if (u->left != nullptr) q.push(u->left);
                if (u->right != nullptr) q.push(u->right);
            }
            ans.push_back(v);
        }
        return ans;
    }
};
posted on 2018-09-03 16:48  Beserious  阅读(179)  评论(0编辑  收藏  举报