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) { vector<vector<int>> ans; queue<TreeNode *> que; if(!root) return ans; que.push(root); while(!que.empty()){ vector<int> temp; //一层地元素 for(int i=que.size();i>0;i--) { TreeNode *t=que.front(); que.pop(); temp.push_back(t->val); if(t->left) que.push(t->left); if(t->right) que.push(t->right); } ans.push_back(temp); //插入到ans数组中 } return ans; } };