二叉树的层次遍历

来源:互联网 发布:写java源代码的步骤 编辑:程序博客网 时间:2024/06/13 23:35

题目描述:二叉树的层次遍历


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


思路:使用一个队列实现。用两个计数器,一个记录这一层完全二叉树该有的节点个数,另一个记录这一层缺失的节点个数。


代码:

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) {
        // write your code here
    vector<vector<int>>v;
         if(root==NULL)   return v;
         vector<int>d;
         queue<TreeNode*>q;
        q.push(root);
        int i=1;
        int j=0;
        while(!q.empty()){
            TreeNode *p=q.front();
            q.pop();
            if(p==NULL) {
                ++j;
            }
            else {
                d.push_back(p->val);
                q.push(p->left);
                q.push(p->right);
            }
            if(i==(d.size()+j)&&d.size()!=0){
                v.push_back(d);
                d.clear();
                i=i*2;
                j=j*2;
            }
        }
        return v;
    }
};


感想:这道题我不会,从网上找的代码,看代码学会了怎么定义队列。

1 0
原创粉丝点击