牛客网剑指offer-从上往下打印二叉树

题目描述

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



/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    //BFS
    vector PrintFromTopToBottom(TreeNode* root) {
        vector ans;
        if (root == nullptr)
            return ans;
        queue q;
        q.push(root);
        while (!q.empty())
        {
            TreeNode *p = q.front();
            ans.push_back(p->val);
            if (p->left != nullptr)
                q.push(p->left);
            if (p->right != nullptr)
                q.push(p->right);
            q.pop();
        }
        return ans;
    }
};

你可能感兴趣的:(剑指offer)