剑指Offer:22-从上往下打印二叉树

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

思路

实现

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    vector PrintFromTopToBottom(TreeNode* root) {
        vector res;
        if(!root)
            return res;
        queue q;
        q.push(root);
        while(!q.empty())
        {
            int len = q.size();
            for(int i = 0; i < len; i++)
            {
                TreeNode* r = q.front();
                q.pop();
                res.push_back(r->val);
                if(r->left)    q.push(r->left);
                if(r->right)    q.push(r->right);
            }
        }
        return res;
    }
};

你可能感兴趣的:(剑指Offer:22-从上往下打印二叉树)