102. Binary Tree Level Order Traversal

来源:互联网 发布:淘宝商家贷款 编辑:程序博客网 时间:2024/04/28 23:02

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


对一棵树层序遍历,以向量形式表示每一行,最后组成向量返回。


代码:

class Solution{public:vector<vector<int> > levelOrder(TreeNode* root) {vector<vector<int> > res;if(!root) return res;queue<TreeNode*>q;q.push(root);while(!q.empty()){int n = q.size();vector<int> vec;for(int i = 0; i < n; ++i){TreeNode* tmp = q.front();q.pop();vec.push_back(tmp->val);if(tmp->left) q.push(tmp->left);if(tmp->right) q.push(tmp->right);}res.push_back(vec);}return res;}};


0 0