Leetcode 102 Binary Tree Level Order Traversal

2018-01-12 14:55:25 浏览数 (4)

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],

代码语言:javascript复制
    3
   / 
  9  20
    /  
   15   7

return its level order traversal as:

代码语言:javascript复制
[
  [3],
  [9,20],
  [15,7]
]

二叉树层次遍历。

队列BFS。

代码语言:javascript复制
/**
 * 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) {
        vector<vector<int>> res;
        vector<int> temp;
        queue<TreeNode*> q,q2;
        q.push(root);
        while(!q.empty() || !q2.empty())
        {
            if(q.empty())
            {
                swap(q,q2);
                res.push_back(temp);
                temp.clear();
            }
            TreeNode* first=q.front();
            q.pop();
            if(!first)continue;
            temp.push_back(first->val);
            q2.push(first->left);
            q2.push(first->right);
        }
        return res;
    }
};

0 人点赞