二叉树的层次遍历

来源:互联网 发布:visor是什么软件 编辑:程序博客网 时间:2024/06/03 23:00

给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)

样例

给一棵二叉树 {3,9,20,#,#,15,7} :

  3 / \9  20  /  \ 15   7

返回他的分层遍历结果:

[  [3],  [9,20],  [15,7]]
解题思路:建立两个队列滚动数组进行循环每次统计一层的结点,当两个队列都为空时跳出循环。
class Solution {    /**     * @param root: The root of binary tree.     * @return: Level order a list of lists of integer     */public:    vector<vector<int>>ans;    vector<vector<int>> levelOrder(TreeNode *root) {         if(root==NULL)return ans;         queue<TreeNode *>tem[2];         tem[0].push(root);         int i=0;         while(!tem[0].empty()||!tem[1].empty()){             vector<int>t;             while(!tem[i].empty()){                 t.push_back(tem[i].front()->val);                 if(tem[i].front()->left!=NULL)tem[(i+1)%2].push(tem[i].front()->left);                 if(tem[i].front()->right!=NULL)tem[(i+1)%2].push(tem[i].front()->right);                 tem[i].pop();             }            ans.push_back(t);             i=(i+1)%2;         }      return ans;            }};


0 0