-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTree.cpp
85 lines (71 loc) · 1.9 KB
/
Tree.cpp
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
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
#include "Tree.h"
TreeNode* CreateTreeNode(int value)
{
TreeNode* pNode = new TreeNode();
pNode->m_nValue = value;
return pNode;
}
void ConnectTreeNodes(TreeNode* pParent, TreeNode* pChild)
{
if(pParent != nullptr)
{
pParent->m_vChildren.push_back(pChild);
}
}
void PrintTreeNode(const TreeNode* pNode)
{
if(pNode != nullptr)
{
printf("value of this node is: %d.\n", pNode->m_nValue);
printf("its children is as the following:\n");
std::vector<TreeNode*>::const_iterator i = pNode->m_vChildren.begin();
while(i < pNode->m_vChildren.end())
{
if(*i != nullptr)
printf("%d\t", (*i)->m_nValue);
}
printf("\n");
}
else
{
printf("this node is nullptr.\n");
}
printf("\n");
}
void PrintTree(const TreeNode* pRoot)
{
PrintTreeNode(pRoot);
if(pRoot != nullptr)
{
std::vector<TreeNode*>::const_iterator i = pRoot->m_vChildren.begin();
while(i < pRoot->m_vChildren.end())
{
PrintTree(*i);
++i;
}
}
}
void DestroyTree(TreeNode* pRoot)
{
if(pRoot != nullptr)
{
std::vector<TreeNode*>::iterator i = pRoot->m_vChildren.begin();
while(i < pRoot->m_vChildren.end())
{
DestroyTree(*i);
++i;
}
delete pRoot;
}
}