题解 | #从上往下打印二叉树#

从上往下打印二叉树

https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
#include <queue>
#include <vector>
class Solution {
public:
	
    vector<int> PrintFromTopToBottom(TreeNode* root) {
		vector<int> v;
		if (!root) return v;
		// 题目意思就是层序遍历
		queue<TreeNode*> q;
		q.push(root);
		while (!q.empty()) {
			int num = q.size();
			for(int i = 0; i < num; ++i)
			{
				TreeNode* tmp = q.front();
				q.pop();
				if(tmp) v.push_back(tmp->val);
				if (tmp->left) {
					q.push(tmp->left);
				}
				if(tmp->right)
				{
					q.push(tmp->right);
				}
			}
		}
		return v;
    }
};

挤挤刷刷! 文章被收录于专栏

记录coding过程

全部评论

相关推荐

10-13 13:49
南京大学 财务
饿魔:笑死我了,你简直是个天才
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务