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

// test20.cpp : 定义控制台应用程序的入口点。
//

include "stdafx.h"

include

include

include

include

include

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 PrintFromTopToBottom(TreeNode root) {
vector vec;
queue<TreeNode
> qu;
if (root == NULL)return vec;
qu.push(root);
while (!qu.empty())
{
//cout << qu.front()->val << " ";
vec.push_back(qu.front()->val);
if (qu.front()->left != NULL) qu.push(qu.front()->left);
if (qu.front()->right != NULL) qu.push(qu.front()->right);
qu.pop();
}
return vec;
}

void preCreate(TreeNode* &T)
{
int num;
cin >> num;
if (num == 0) T = NULL;
else
{
T = new TreeNode(num);
preCreate(T->left);
preCreate(T->right);
}
}

void preOrder(TreeNode* T)
{
if (T == NULL) return;
else
{
cout << T->val << " ";
preOrder(T->left);
preOrder(T->right);
}
}
};
int main()
{

Solution so;
TreeNode *T1;
TreeNode *T2;
vector vec;

cout << "创建T1:" << endl;
so.preCreate(T1);
cout << "创建T1成功!" << endl;

cout << "T1的前序遍历:" << endl;
so.preOrder(T1);
cout << endl;

vec = so.PrintFromTopToBottom(T1);

cout << "层次遍历的结果是:" << endl;
for (auto it = vec.begin();it != vec.end();it++)
cout << *it << " ";

cout << endl;
return 0;
}

posted @ 2016-10-23 21:48  wdan2016  阅读(204)  评论(0)    收藏  举报