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

来源:互联网 发布:上海房价还会涨吗 知乎 编辑:程序博客网 时间:2024/06/05 21:20

题目:从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。广度优先遍历。

#include <deque>#include <iostream>using namespace std;struct BinaryTreeNode {  int m_nValue;  BinaryTreeNode *m_pLeft;  BinaryTreeNode *m_pRight;};BinaryTreeNode *CreateTree() {  int a;  cin >> a;  if (a != -1) {    BinaryTreeNode *root = new BinaryTreeNode;    root->m_nValue = a;    cout << "请输入" << a << "的左结点:";    root->m_pLeft = CreateTree();    cout << "请输入" << a << "的右结点:";    root->m_pRight = CreateTree();    return root;  }  return NULL;}void PrintTree(BinaryTreeNode *root) {  if (root == NULL)    return;  deque<BinaryTreeNode *> TreeNode;  TreeNode.push_back(root);  while (TreeNode.size()) {    BinaryTreeNode *pNode = TreeNode.front();    TreeNode.pop_front();    cout << pNode->m_nValue << " ";    if (pNode->m_pLeft != NULL)      TreeNode.push_back(pNode->m_pLeft);    if (pNode->m_pRight != NULL)      TreeNode.push_back(pNode->m_pRight);  }}int main() {  BinaryTreeNode *root = CreateTree();  PrintTree(root);  cout << endl;  return 0;}
0 0
原创粉丝点击