C++ 从上到下,从左至右打印二叉树

代码如下:

#include 
#include "BinaryTree.h"
#include 
using namespace std;
void PrintTree_from_head_to_tail(TreeNode* proot)
{
	if(proot == NULL)
		return;
	deque  tree_que;
	TreeNode* node = proot;
	tree_que.push_back(node);
	while(!tree_que.empty())
	{
		node = tree_que.front();
		if(node ->pLeft != NULL)
			tree_que.push_back(node ->pLeft);
		if(node ->pRight != NULL)
			tree_que.push_back(node ->pRight);
		cout << node->m_value <<'\t';
		tree_que.pop_front();
	}
}
// ====================测试代码====================
void Test(char* testName, TreeNode* pRoot)
{
    if(testName != NULL)
        printf("%s begins: \n", testName);

    printf("The nodes from top to bottom, from left to right are: \n");
    PrintTree_from_head_to_tail(pRoot);

    printf("\n\n");
}

//            10
//         /      \
//        6        14
//       /\        /\
//      4  8     12  16
void Test1()
{
    TreeNode* pNode10 = CreateNode(10);
    TreeNode* pNode6 = CreateNode(6);
    TreeNode* pNode14 = CreateNode(14);
    TreeNode* pNode4 = CreateNode(4);
    TreeNode* pNode8 = CreateNode(8);
    TreeNode* pNode12 = CreateNode(12);
    TreeNode* pNode16 = CreateNode(16);

    ConnectNodes(pNode10, pNode6, pNode14);
    ConnectNodes(pNode6, pNode4, pNode8);
    ConnectNodes(pNode14, pNode12, pNode16);

    Test("Test1", pNode10);

    DestroyTree(pNode10);
}

//               5
//              /
//             4
//            /
//           3
//          /
//         2
//        /
//       1
void Test2()
{
    TreeNode* pNode5 = CreateNode(5);
    TreeNode* pNode4 = CreateNode(4);
    TreeNode* pNode3 = CreateNode(3);
    TreeNode* pNode2 = CreateNode(2);
    TreeNode* pNode1 = CreateNode(1);

    ConnectNodes(pNode5, pNode4, NULL);
    ConnectNodes(pNode4, pNode3, NULL);
    ConnectNodes(pNode3, pNode2, NULL);
    ConnectNodes(pNode2, pNode1, NULL);

    Test("Test2", pNode5);

    DestroyTree(pNode5);
}

// 1
//  \
//   2
//    \
//     3
//      \
//       4
//        \
//         5
void Test3()
{
    TreeNode* pNode1 = CreateNode(1);
    TreeNode* pNode2 = CreateNode(2);
    TreeNode* pNode3 = CreateNode(3);
    TreeNode* pNode4 = CreateNode(4);
    TreeNode* pNode5 = CreateNode(5);

    ConnectNodes(pNode1, NULL, pNode2);
    ConnectNodes(pNode2, NULL, pNode3);
    ConnectNodes(pNode3, NULL, pNode4);
    ConnectNodes(pNode4, NULL, pNode5);

    Test("Test3", pNode1);

    DestroyTree(pNode1);
}

// 树中只有1个结点
void Test4()
{
    TreeNode* pNode1 = CreateNode(1);
    Test("Test4", pNode1);

    DestroyTree(pNode1);
}

// 树中没有结点
void Test5()
{
    Test("Test5", NULL);
}

int main()
{
    Test1();
    Test2();
    Test3();
    Test4();
    Test5();
	system("PAUSE");
	return 0;
}

运行结果如下:

C++ 从上到下,从左至右打印二叉树_第1张图片

你可能感兴趣的:(C++)