【剑指offer 面试题23】从上往下打印二叉树

思路:

  没啥好说的,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);
}

测试结果:


从上往下打印二叉树:      
上一篇:Tomcat远程调试catalina.sh的配置


下一篇:C++版 - 剑指offer 面试题39:判断平衡二叉树(LeetCode 110. Balanced Binary Tree) 题解