LeetCode-Binary Tree Level Order Traversal

对二叉树进行层序遍历,具体可以参考二叉树相关知识点总结

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* 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>> result;
if(root==nullptr) return result;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int n=q.size();
vector<int> tRes;
for(int i=0;i<n;i++){
TreeNode* t=q.front();
q.pop();
tRes.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
result.push_back(tRes);
}
return result;
}
};