problem:
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,#,#,15,7}
,
3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
confused what "{1,#,2,3}"
means? >
read more on how binary tree is serialized on OJ.
Hide Tags
题意:层序遍历二叉树,每层要分开
thinking:
(1)普通的二叉树层序遍历算法每层是没有分开的,这道题要求分开。
(2)采用广度优先搜索(BFS)的思想
(3)采用两个queue,递归实现每层分开的层序遍历,很经典
code:
class Solution { private: vector<vector<int> > ret; public: vector<vector<int> > levelOrder(TreeNode *root) { ret.clear(); if(root==NULL) return ret; queue<TreeNode *> tmp_queue; tmp_queue.push(root); level_order(tmp_queue); return ret; } void level_order(queue<TreeNode *> queue1) { if(queue1.empty()) return; vector<int> array; queue<TreeNode *> queue2; while(!queue1.empty()) { TreeNode *tmp=queue1.front(); array.push_back(tmp->val); queue1.pop(); if(tmp->left!=NULL) queue2.push(tmp->left); if(tmp->right!=NULL) queue2.push(tmp->right); } ret.push_back(array); level_order(queue2); } };
时间: 2024-11-06 11:14:33