mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 102. Binary Tree Level Order Traversal.md
This commit is contained in:
parent
1549ad4e8f
commit
57309a28cc
32
solutions/102. Binary Tree Level Order Traversal.md
Normal file
32
solutions/102. Binary Tree Level Order Traversal.md
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
# [102. Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)
|
||||||
|
# 思路
|
||||||
|
层序遍历二叉树。已经在[107题题解](https://github.com/ShusenTang/LeetCode/blob/master/solutions/107.%20Binary%20Tree%20Level%20Order%20Traversal%20II.md)分析过了。
|
||||||
|
|
||||||
|
时空复杂度均O(n)
|
||||||
|
|
||||||
|
# C++
|
||||||
|
``` C++
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
vector<vector<int>> levelOrder(TreeNode* root) {
|
||||||
|
vector<vector<int>>res;
|
||||||
|
if(root == NULL) return res;
|
||||||
|
queue<TreeNode *>q;
|
||||||
|
TreeNode *p;
|
||||||
|
|
||||||
|
q.push(root);
|
||||||
|
while(!q.empty()){
|
||||||
|
vector<int>level;
|
||||||
|
for(int i = q.size(); i > 0; i--){
|
||||||
|
p = q.front();
|
||||||
|
q.pop();
|
||||||
|
level.push_back(p -> val);
|
||||||
|
if(p -> left) q.push(p -> left);
|
||||||
|
if(p -> right) q.push(p -> right);
|
||||||
|
}
|
||||||
|
res.push_back(level);
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user