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] ]
层次遍历
C++:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> levelOrder(TreeNode* root) { 13 if (root == NULL) 14 return vector<vector<int>>() ; 15 vector<vector<int>> res ; 16 vector<int> level ; 17 queue<TreeNode*> q ; 18 q.push(root) ; 19 while(!q.empty()){ 20 int len = q.size() ; 21 for(int i = 0 ; i < len ; i++){ 22 TreeNode* temp = q.front() ; 23 q.pop() ; 24 if (temp->left != NULL) 25 q.push(temp->left) ; 26 if (temp->right != NULL) 27 q.push(temp->right) ; 28 level.push_back(temp->val) ; 29 } 30 res.push_back(level) ; 31 level.clear() ; 32 } 33 return res; 34 } 35 };