给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7]
,
3 / 9 20 / 15 7
返回其层次遍历结果:
[ [3], [9,20], [15,7] ]
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 11 class Solution { 12 public: 13 vector<vector<int>> levelOrder(TreeNode* root) { 14 queue<TreeNode*> q; 15 q.push(root); 16 vector<vector<int>> ans; 17 if(root == NULL) return ans; 18 while(!q.empty()){ 19 queue<TreeNode*> qt; 20 vector<int> t; 21 while(!q.empty()){ 22 TreeNode* temp = q.front(); 23 q.pop(); 24 t.push_back(temp->val); 25 if(temp->left) qt.push(temp->left); 26 if(temp->right) qt.push(temp->right); 27 } 28 ans.push_back(t); 29 q = qt; 30 } 31 return ans; 32 } 33 };