二叉树的层次遍历

来源:互联网 发布:西部数码域名管理 编辑:程序博客网 时间:2024/06/05 11:29

一、问题描述

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

二、样例

给一棵二叉树 {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
    }
};

0 0