-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path32_1_Print_BinaryTree_Level_Order.cpp
More file actions
144 lines (102 loc) · 2.59 KB
/
32_1_Print_BinaryTree_Level_Order.cpp
File metadata and controls
144 lines (102 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
//
// Created by mark on 2019/7/12.
// Copyright © 2019年 mark. All rights reserved.
//
/*
说明:
1. 问题:32.从上到下打印二叉树。
2. 思路:层次遍历,用队列
*/
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <assert.h>
using namespace std;
struct BinaryTreeNode
{
int val;
BinaryTreeNode* left;
BinaryTreeNode* right;
}TN,*pTN;
// 层序遍历
void LevelOrder(BinaryTreeNode* root)
{
if(root == nullptr)
return;
queue<BinaryTreeNode*> q;
q.push(root);
while(!q.empty())
{
BinaryTreeNode* pNode = q.front();
q.pop();
cout << pNode->val << " ";
if(pNode->left != nullptr)
q.push(pNode->left);
if(pNode->right != nullptr)
q.push(pNode->right);
}
}
//辅助函数 ------------------------------------------------------------------------------------------------------------------------
// 构建树节点
BinaryTreeNode* CreateTreeNode(int val)
{
BinaryTreeNode* pNode = new BinaryTreeNode();
pNode->val = val;
pNode->left = nullptr;
pNode->right = nullptr;
return pNode;
}
// 连接树节点
void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight)
{
if(pParent != nullptr)
{
pParent->left = pLeft;
pParent->right = pRight;
}
}
// 销毁树
void DestroyTree(BinaryTreeNode* root)
{
if(root != nullptr)
{
BinaryTreeNode* left = root->left;
BinaryTreeNode* right = root->right;
delete root;
root = nullptr;
DestroyTree(left);
DestroyTree(right);
}
}
// 先序打印树
void PrintPreOrder(BinaryTreeNode* root)
{
if(root == nullptr)
return;
cout << root->val << " ";
PrintPreOrder(root->left);
PrintPreOrder(root->right);
}
int main(){
BinaryTreeNode* p1 = CreateTreeNode(1);
BinaryTreeNode* p2 = CreateTreeNode(2);
BinaryTreeNode* p3 = CreateTreeNode(3);
BinaryTreeNode* p4 = CreateTreeNode(4);
BinaryTreeNode* p5 = CreateTreeNode(5);
BinaryTreeNode* p6 = CreateTreeNode(6);
BinaryTreeNode* p7 = CreateTreeNode(7);
ConnectTreeNodes(p1, p2, p3);
ConnectTreeNodes(p2, p4, p5);
ConnectTreeNodes(p3, p6, nullptr);
ConnectTreeNodes(p4, p7, nullptr);
cout << "先序打印二叉树为:";
PrintPreOrder(p1);
cout << endl;
cout << "层次遍历二叉树为:";
LevelOrder(p1);
cout << endl;
return 0;
}