面试题23 从上往下打印二叉树

代码:

[cpp]  view plain copy
  1. #include "stdafx.h"  
  2. #include <iostream>  
  3. #include <deque>  
  4. using namespace std;  
  5.   
  6. struct BinaryTreeNode  
  7. {  
  8.     int m_nValue;  
  9.     BinaryTreeNode *m_pLeft;  
  10.     BinaryTreeNode *m_pRight;  
  11. };  
  12.   
  13. void PrintFromTopToDown(BinaryTreeNode *pRoot)  
  14. {  
  15.     if (pRoot == NULL)  
  16.     {  
  17.         return;  
  18.     }  
  19.   
  20.     deque<BinaryTreeNode *> myDeque;  
  21.     myDeque.push_back(pRoot);  
  22.     while (!myDeque.empty())  
  23.     {  
  24.         BinaryTreeNode *pTop = myDeque.front();  
  25.         cout << pTop->m_nValue << " ";  
  26.         myDeque.pop_front();  
  27.   
  28.         if (pTop->m_pLeft != NULL)  
  29.         {  
  30.             myDeque.push_back(pTop->m_pLeft);  
  31.         }  
  32.   
  33.         if (pTop->m_pRight != NULL)  
  34.         {  
  35.             myDeque.push_back(pTop->m_pRight);  
  36.         }  
  37.     }  
  38. }  
  39.   
  40. //以先序的方式构建二叉树,输入-1表示结点为空  
  41. void CreateBinaryTree(BinaryTreeNode *&pRoot)  
  42. {  
  43.     int nNodeValue = 0;  
  44.     cin >> nNodeValue;      
  45.     if (-1 == nNodeValue)  
  46.     {  
  47.         return;   
  48.     }  
  49.     else  
  50.     {  
  51.         pRoot = new BinaryTreeNode();  
  52.         pRoot->m_nValue = nNodeValue;  
  53.         CreateBinaryTree(pRoot->m_pLeft);  
  54.         CreateBinaryTree(pRoot->m_pRight);  
  55.     }  
  56. }  
  57.   
  58. void PrintInOrder(BinaryTreeNode *&pRoot)  
  59. {  
  60.     if (pRoot != NULL)  
  61.     {  
  62.         PrintInOrder(pRoot->m_pLeft);  
  63.         cout << pRoot->m_nValue << " ";  
  64.         PrintInOrder(pRoot->m_pRight);  
  65.     }  
  66. }  
  67.   
  68. int _tmain(int argc, _TCHAR* argv[])  
  69. {  
  70.     BinaryTreeNode *pRoot = NULL;  
  71.     CreateBinaryTree(pRoot);  
  72.     PrintInOrder(pRoot);  
  73.     cout << endl;  
  74.     PrintFromTopToDown(pRoot);  
  75.     cout << endl;  
  76.     system("pause");  
  77.     return 0;  
  78. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值