【LeetCode 】102. Binary Tree Level Order Traversal
阿新 • • 發佈:2019-01-23
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
其實就是樹的廣度優先搜尋,使用佇列進行輔助,遍歷每一層
/**
* 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>> res;
if (root == NULL) return res;
vector<int> sub; // 儲存每一層每個結點的值
queue<TreeNode *> q; // 輔助佇列
q.push(root);
while (!q.empty()) { // q為空時結束迴圈
queue<TreeNode *> tmpq; // 臨時佇列,儲存下一層的結點
while (!q.empty()) {
sub.push_back(q.front()->val); // 將該層節點值加入sub中
if (q.front()->left != NULL) tmpq.push(q.front()->left); // 依次將左右子結點放入佇列中
if (q.front()->right != NULL) tmpq.push(q.front()->right);
q.pop(); // 彈出一個結點,為空時表明當前層的所有結點都被遍歷過
}
res.push_back(sub); // 加入結果集
q = tmpq; // 更新佇列
sub.clear(); // 清空,以備下次使用
}
return res;
}
};