zoukankan      html  css  js  c++  java
  • 面试题21:从上往下打印二叉树

    代码:

    #include "stdafx.h"
    #include <iostream>
    #include <deque>
    using namespace std;
    
    struct BinaryTreeNode
    {
    	int m_nValue;
    	BinaryTreeNode *m_pLeft;
    	BinaryTreeNode *m_pRight;
    };
    
    void PrintFromTopToDown(BinaryTreeNode *pRoot)
    {
    	if (pRoot == NULL)
    	{
    		return;
    	}
    
        deque<BinaryTreeNode *> myDeque;
    	myDeque.push_back(pRoot);
    	while (!myDeque.empty())
    	{
            BinaryTreeNode *pTop = myDeque.front();
    		cout << pTop->m_nValue << " ";
    		myDeque.pop_front();
    
    		if (pTop->m_pLeft != NULL)
    		{
    			myDeque.push_back(pTop->m_pLeft);
    		}
    
    		if (pTop->m_pRight != NULL)
    		{
    			myDeque.push_back(pTop->m_pRight);
    		}
    	}
    }
    
    //以先序的方式构建二叉树,输入-1表示结点为空
    void CreateBinaryTree(BinaryTreeNode *&pRoot)
    {
    	int nNodeValue = 0;
    	cin >> nNodeValue;	
    	if (-1 == nNodeValue)
    	{
    		return; 
    	}
    	else
    	{
    		pRoot = new BinaryTreeNode();
    		pRoot->m_nValue = nNodeValue;
    		CreateBinaryTree(pRoot->m_pLeft);
    		CreateBinaryTree(pRoot->m_pRight);
    	}
    }
    
    void PrintInOrder(BinaryTreeNode *&pRoot)
    {
    	if (pRoot != NULL)
    	{
    		PrintInOrder(pRoot->m_pLeft);
    		cout << pRoot->m_nValue << " ";
    		PrintInOrder(pRoot->m_pRight);
    	}
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	BinaryTreeNode *pRoot = NULL;
    	CreateBinaryTree(pRoot);
    	PrintInOrder(pRoot);
    	cout << endl;
        PrintFromTopToDown(pRoot);
    	cout << endl;
    	system("pause");
    	return 0;
    }
    



  • 相关阅读:
    Windows:生成环境Word,PPT,EXCEL com+组件配置
    Win10 计算机管理 打不开应急办法
    Js:弹窗剧中
    Asp.net跨域配置
    Centos6系列安装nginx
    Win_oracle_exp/expdp备份
    MSSQL:查看某个账号使用得数据库
    MSSQL:查看作业情况
    MSSQL:账号无法删除方案
    MSSQL:删除系统作业计划
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3206379.html
Copyright © 2011-2022 走看看