您的位置:首页 > 职场人生

【剑指offer】4.3举例让抽象问题具体化——面试题23:从上往下打印二叉树

2016-01-11 20:41 603 查看




//题目描述
//
//从上往下打印出二叉树的每个节点,同层节点从左至右打印。
#include<iostream>
#include<windows.h>
#include<vector>
#include<queue>
using namespace std;
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>res;
if(root==NULL)return res;
queue<TreeNode*>q;
TreeNode *p=root;
q.push(p);
while(!q.empty()){
p=q.front();
q.pop();
res.push_back(p->val);
if(p->left!=NULL)q.push(p->left);
if(p->right!=NULL)q.push(p->right);
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: