LeetcCode102 Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). (Easy)
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] ]
分析:
层序遍历,就是BFS的思路,利用队列把每一行的节点存进去,然后一行一行读出。
注意每次循环用读取size的方式确定这一行到哪里结束。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 private: 12 vector<vector<int>> result; 13 public: 14 vector<vector<int>> levelOrder(TreeNode* root) { 15 if (root == nullptr) { 16 return result; 17 } 18 queue<TreeNode* > que; 19 que.push(root); 20 while (!que.empty()) { 21 int sz = que.size(); 22 vector<int> temp; 23 for (int i = 0; i < sz; ++i) { 24 TreeNode* cur = que.front(); 25 que.pop(); 26 temp.push_back(cur -> val); 27 if (cur -> left != nullptr) { 28 que.push(cur -> left); 29 } 30 if (cur -> right != nullptr) { 31 que.push(cur -> right); 32 } 33 } 34 result.push_back(temp); 35 } 36 return result; 37 } 38 };