69.二叉树的层次遍历

来源:互联网 发布:图像空间的消隐算法 编辑:程序博客网 时间:2024/06/16 17:25

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


样例:

给一棵二叉树 {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:    std::vector<int> f;    std::vector<vector <int>> w;    vector<vector<int>> levelOrder(TreeNode *root) {    // write your code here        if(root==NULL) return w;        queue <TreeNode*> q;        q.push(root);        int length;        while(!q.empty())        {            length=q.size();            while(length!=0)            {                TreeNode *t=q.front();                f.push_back(t->val);                q.pop();                length--;                if(t->left!=NULL)                q.push(t->left);                if(t->right!=NULL)                q.push(t->right);            }            w.push_back(f);            f.clear();        }        return w;    }};
感想:层次遍历相比前中后序遍历要略微麻烦一点,建立两个向量,分别表示遍历后的两种格式,然后使用队列的特点,先进先出,进行遍历。

0 0