# Leetcode [No. 102] Binary Tree Level Order Traversal (MEDIUM) ## 題目 https://leetcode.com/problems/binary-tree-level-order-traversal/description/ ## 思路 + 這個解法其實就是用簡單的BFS來完成level order traversal. + 在每次pop之前都先去計算目前的queue有多少個element + 如此一來我們就可以知道在這次新增了多少個element ```c++= /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> ans; if(root == NULL) return ans; queue<TreeNode*> q; q.push(root); while(!q.empty()) { int levelSize = q.size(); // the size is queue size vector<int> vec; for(int i = 0 ;i < levelSize; i++) { TreeNode* current = q.front(); vec.push_back(current->val); q.pop(); if(current->left != NULL) q.push(current->left); if(current->right != NULL) q.push(current->right); } ans.push_back(vec); } return ans; } }; ``` ### 解法分析 + time complexity: O(n) ### 執行結果  --- ## 二訪@2025/04/27 ```c++= class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { if (!root) return {}; queue<TreeNode*> q; q.push(root); vector<vector<int>> res; while(!q.empty()){ int size = q.size(); vector<int> v(size); for (int i = 0 ; i < size; i++) { TreeNode* cur = q.front(); q.pop(); if (cur->left) q.push(cur->left); if (cur->right) q.push(cur->right); v[i] = cur->val; } res.emplace_back(v); } return res; } }; ``` 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up