实现一棵二叉树的层序遍历

来源:互联网 发布:mac地址表包括vlan吗 编辑:程序博客网 时间:2024/05/18 23:56

BinaryTree.h

#pragma once#include <iostream>#include<deque>using namespace std;struct BinaryTreeNode{    int _value;    BinaryTreeNode* _pLeft;    BinaryTreeNode* _pRight;};

PrintBinaryTree.cpp

#include"BinaryTree.h"void PrintFromTopToBottom(BinaryTreeNode* pTreeRoot){    if (!pTreeRoot)        return ;    deque<BinaryTreeNode*> dequeTreeNode;    dequeTreeNode.push_back(pTreeRoot);    while (dequeTreeNode.size())    {        BinaryTreeNode* pNode = dequeTreeNode.front();        cout<<pNode->_value;        dequeTreeNode.pop_front();        if (pNode->_pLeft)            dequeTreeNode.push_back(pNode->_pLeft);        if (pNode->_pRight)            dequeTreeNode.push_back(pNode->_pRight);    }}void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight){    if(pParent != NULL)    {        pParent->_pLeft = pLeft;        pParent->_pRight = pRight;    }}BinaryTreeNode* CreateBinaryTreeNode(int value){    BinaryTreeNode* pNode = new BinaryTreeNode();    pNode->_value = value;    pNode->_pLeft = NULL;    pNode->_pRight = NULL;    return pNode;}void test(){    BinaryTreeNode* pNode10 = CreateBinaryTreeNode(10);    BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);    BinaryTreeNode* pNode14 = CreateBinaryTreeNode(14);    BinaryTreeNode* pNode4 = CreateBinaryTreeNode(4);    BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);    BinaryTreeNode* pNode12 = CreateBinaryTreeNode(12);    BinaryTreeNode* pNode16 = CreateBinaryTreeNode(16);    ConnectTreeNodes(pNode10, pNode6, pNode14);    ConnectTreeNodes(pNode6, pNode4, pNode8);    ConnectTreeNodes(pNode14, pNode12, pNode16);    PrintFromTopToBottom(pNode10);}int main(){    test();    return 0;}
原创粉丝点击