您的位置:首页 > 其它

二叉树的层次遍历

2017-04-29 22:47 190 查看
一、问题描述

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

二、样例

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


返回他的分层遍历结果:
[
[3],
[9,20],
[15,7]
]

三、思路
将每层的节点入对然后依次出队,再将出队节点的下一层保存,并将出队节点存入向量中,层层进行,直到最后一层。

四、代码

/**

 * Definition of TreeNode:

 * class TreeNode {

 * public:

 *     int val;

 *     TreeNode *left, *right;

 *     TreeNode(int val) {

 *         this->val = val;

 *         this->left = this->right = NULL;

 *     }

 * }

 */

 

 

class Solution {

    /**

     * @param root: The root of binary tree.

     * @return: Level order a list of lists of integer

     */

public:

    vector<vector<int>> levelOrder(TreeNode *root) {

          vector<vector<int>> result;  

        queue<TreeNode*>q;              

        vector<int> level;       //每层结果  

        int size,i;  

        TreeNode* p;  

          if(root==NULL) return result;  

        q.push(root);            //入队  

        while(!q.empty())

        {  //队列中有几个元素就依次遍历每个元素的左右结点  

            level.clear();  

            size=q.size();  

            for(i=0; i<size; i++)

            {  

                p=q.front();     //队首元素值赋给p  

                q.pop();         //出队  

                level.push_back(p->val);  

                if(p->left)

               {    //依次压入左右结点元素  

                    q.push(p->left);  

                }  

                if(p->right)

               {  

                    q.push(p->right);

                }  

            }  

            result.push_back(level);   //添加每层数据  

        }  

        return result;

        // write your code here

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: