思路:

  没啥好说的,BFS。

C++:

 #include <iostream>
#include <queue>
using namespace std; struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
}; void PrintFromTop2Bottom(TreeNode *root)
{
if(root == )
return ; queue<TreeNode* > QueueTreeNode; QueueTreeNode.push(root); while(!QueueTreeNode.empty())
{
TreeNode *temp = QueueTreeNode.front();
cout<<temp->val<<" ";
QueueTreeNode.pop(); if(temp->left != )
QueueTreeNode.push(temp->left);
if(temp->right != )
QueueTreeNode.push(temp->right);
}
} int main()
{
TreeNode *Root = new TreeNode();
TreeNode *node1 = new TreeNode();
TreeNode *node2 = new TreeNode();
TreeNode *node3 = new TreeNode();
TreeNode *node4 = new TreeNode();
TreeNode *node5 = new TreeNode();
TreeNode *node6 = new TreeNode(); Root->left = node1;
Root->right = node2;
node1->left = node3;
node1->right = node4;
node2->left = node5;
node2->right = node6; cout<<""<<endl;
cout<<" 1 2"<<endl;
cout<<"3 4 5 6"<<endl<<endl; cout<<"从上往下打印二叉树:";
PrintFromTop2Bottom(Root);
}

测试结果:


从上往下打印二叉树:      
04-14 06:05