剑指offer 从上往下打印二叉树

剑指offer 从上往下打印二叉树

  • 题目描述

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

  • 解法实现
/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    vector<int> PrintFromTopToBottom(TreeNode *root) {
		vector<int> ret;
		if (root == NULL)
			return ret;
		queue<TreeNode*> q;
		q.push(root);
		while (!q.empty()){
			TreeNode* t = q.front();
			ret.push_back(t->val);
			if (t->left != NULL)
				q.push(t->left);
			if (t->right != NULL)
				q.push(t->right);
			q.pop();
		}
		return ret;
    }
};
弹钢琴的猫 /
Published under (CC) BY-NC-SA in categories 算法  tagged with 剑指offer  queue