Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 从上往下打印二叉树

从上往下打印出二叉树的每个结点,同一层按照从左到右的顺序打印#include <iostream>
#include <deque>
using namespace std;struct BinaryTreeNode
{
 int data;
 struct BinaryTreeNode *lchild;
 struct BinaryTreeNode *rchild;
};typedef struct BinaryTreeNode BinTreeNode;//先序构造二叉树
BinTreeNode* preOrderCreateTree(BinTreeNode *head)
{
 int tmp;
 cin >> tmp;
 if (tmp == 0)
  head = NULL;
 else
 {
  head = new BinTreeNode;
  head->data = tmp;
  head->lchild = preOrderCreateTree(head->lchild);
  head->rchild = preOrderCreateTree(head->rchild);
 }
 
 return head;
}//先序遍历二叉树
void preVisitTree(const BinTreeNode *head)
{
 if (head == NULL)
  return;
 
 cout << head->data;
 preVisitTree(head->lchild);
 preVisitTree(head->rchild);
}void freeTree(BinTreeNode *head)
{
 if (head == NULL)
  return;
 
 freeTree(head->lchild);
 freeTree(head->rchild);
 delete head;
}void printOrderByLayer(const BinTreeNode *head)
{
 if (head == NULL)
  return;
 
 deque<const BinTreeNode*> myDeque;
 myDeque.push_back(head);
 while (myDeque.size() > 0)
 {
  const BinTreeNode *tmp = myDeque.front();
  myDeque.pop_front();
  cout << tmp->data;
  if (tmp->lchild)
   myDeque.push_back(tmp->lchild);
  if (tmp->rchild)
   myDeque.push_back(tmp->rchild);
 }
}int main()
{
 BinTreeNode *root = preOrderCreateTree(root);
 preVisitTree(root);
 cout << endl;
 printOrderByLayer(root);
 cout << endl;
 freeTree(root); 
 return 0;
}二叉树的常见问题及其解决程序 http://www.linuxidc.com/Linux/2013-04/83661.htm【递归】二叉树的先序建立及遍历 http://www.linuxidc.com/Linux/2012-12/75608.htm在JAVA中实现的二叉树结构 http://www.linuxidc.com/Linux/2008-12/17690.htm【非递归】二叉树的建立及遍历 http://www.linuxidc.com/Linux/2012-12/75607.htm二叉树递归实现与二重指针 http://www.linuxidc.com/Linux/2013-07/87373.htm二叉树先序中序非递归算法 http://www.linuxidc.com/Linux/2014-06/102935.htm轻松搞定面试中的二叉树题目 http://www.linuxidc.com/linux/2014-07/104857.htm本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-09/106592.htm