您的位置:首页 > Web前端

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

2018-08-21 14:55 127 查看

题目

从上往下打印二叉树
时间限制:1秒 空间限制:32768K 热度指数:228450

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

解法

代码

/*
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> result;
if(root==NULL)
return result;

queue<TreeNode*> nodes;
TreeNode* current=NULL;

nodes.push(root);
while(!nodes.empty())
{
current=nodes.front();
nodes.pop();
result.push_back(current->val);
if(current->left!=NULL)
nodes.push(current->left);
if(current->right!=NULL)
nodes.push(current->right);

}
return result;

}
};
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: