本题是广度优先遍历(BFS)实现树的层次遍历,使用队列实现。
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> res; queue<TreeNode*>q; if (root != NULL) { q.push(root); while (!q.empty()) { vector<int> tmp; vector<TreeNode*> T; while (!q.empty()) { TreeNode* t = q.front(); q.pop(); tmp.push_back(t->val); if (t->left != NULL) { T.push_back(t->left); } if (t->right != NULL) { T.push_back(t->right); } } res.push_back(tmp); for (auto x : T) { q.push(x); } } } return res; } };
补充一个python的实现:
1 class Solution: 2 def lOrder(self,temp,result): 3 count = len(temp) 4 newary = [] 5 while count > 0: 6 top = temp.pop(0) 7 newary.append(top.val) 8 count -= 1 9 if top.left != None: 10 temp.append(top.left) 11 if top.right != None: 12 temp.append(top.right) 13 if len(newary) > 0: 14 result.append(newary) 15 if len(temp) > 0: 16 self.lOrder(temp,result) 17 18 def levelOrder(self, root: TreeNode) -> List[List[int]]: 19 result = [] 20 temp = [] 21 if root != None: 22 temp.append(root) 23 self.lOrder(temp,result) 24 return result