> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/102.-binary-tree-level-order-traversal-medium.md).

# 102. Binary Tree Level Order Traversal

## 1.問題

* 給予一個binary tree, 回傳一個level order traversal的node's序列 (例如, 從左到右, 一層接一層)

![](/files/-LH2YSHtHJI40yN6YftE)

## 2.想法

* 可用level-order traversal, 廣度優先搜尋(BFS)的概念:
  * 1.先將root node放入一開始的queue
  * 2.queue當前中的每一個元素若有子樹的, 則加入queue中 (等待下一次)

## 3.程式碼

```
/**
 * 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>> v;
        if (!root) {
            return v;
        }
        queue<TreeNode*> q;
        vector<int> vTemp;
        vTemp.push_back(root->val);
        v.push_back(vTemp);
        q.push(root);
        
        while (!q.empty()){
            vector<int> vTemp;
            int size = q.size();
            for(int i = 0 ; i < size; i++){
                TreeNode* node = q.front();
                q.pop();
                if (node->left){
                    vTemp.push_back(node->left->val);
                    q.push(node->left);
                }
                if (node->right){
                    vTemp.push_back(node->right->val);
                    q.push(node->right);
                }
            }
            if (!vTemp.empty()){
                v.push_back(vTemp);
            }
        }
        return v;
    }
};
```

## 4.Performance

![](/files/-LH2YA-boZ-aNH8ywx54)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/102.-binary-tree-level-order-traversal-medium.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
