lintcode 二叉树的层次遍历

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

2:解题思路:将每一层的数据存到队列里面去,用递归的方法访问,层次依次增加。

3:解题代码:

/**
 * 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:
    std::vector>binary;
    std::vectorbinary2;
    vector> levelOrder(TreeNode *root)
    {
        // write your code here
        queue aqueue;
        TreeNode*pointer=root;
        if(root==NULL)return binary;
        if(pointer) aqueue.push(pointer);int length=1;
        while(!aqueue.empty())//队列非空返回0
        {
            length=aqueue.size();
            while(length--)
            {
            pointer=aqueue.front();
            aqueue.pop();
            binary2.push_back(pointer->val);
            if(pointer->left)
            aqueue.push(pointer->left);
            if(pointer->right)
            aqueue.push(pointer->right);
            }
            binary.push_back(binary2);
            binary2.clear();
        }
        return binary;
    }
};

4:解题感想:

层次遍历的实现比前序中序和后序难,因为还要每一层存到动态数组里去,输出每一层的元素,所以在老师的课件上层序遍历上做些改动就可以解决。做题会暴漏自己的缺点,老师以前讲过STL方面的知识,但是自己忘得比较多,好多函数都是凭着感觉写的,自己还要多看看书,了解了解知识。

你可能感兴趣的:(二叉树)