-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTree.cpp
153 lines (124 loc) · 2.41 KB
/
BinaryTree.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
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
143
144
145
146
147
148
149
150
151
152
#include "stdafx.h"
#include<stdio.h>
#include"string"
#include "vector"
#include "iostream"
#include<algorithm>
using namespace std;
#include <stdio.h>
#include <vector>
#include <string>
#include <queue>
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};
class BinaryTree
{
public:
BinaryTree(vector<string>);
~BinaryTree() {};
void printPreorder();
void printInorder();
void printPostorder();
void printIntire();
int findMaxDepth(TreeNode* temp);
public:
TreeNode * head;
};
BinaryTree::BinaryTree(vector<string>input)
{
if (input.size() < 1)
return;
TreeNode** nodes = new TreeNode*[input.size()];
for (int i = 0; i < input.size(); i++)
{
if (input[i][0] == ' ')
nodes[i] = NULL;
else
nodes[i] = new TreeNode(atoi(input[i].c_str()));
}
int i = 0;
while (i<input.size())
{
if(i*2+1<input.size())
nodes[i]->left = nodes[i * 2+1];
if(i*2+2<input.size())
nodes[i]->right = nodes[i * 2 + 2];
i++;
}
/*//还有一种fangfa
TreeNode* node;
int index = 0;
while(index<input.size())
{
node = queue.front();
queue.pop();
queue.push(node[index++]);
node.left = queue.back();
queue.push(node[index++]);
node.right = queue.back();
}
*/
head = nodes[0];
}
/**
* @param:层次遍历
*/
void BinaryTree::printIntire()
{
queue<TreeNode*> nodeQueue;
TreeNode* tempNode;
nodeQueue.push(head);
while (nodeQueue.empty() == 0)
{
tempNode = nodeQueue.front();
nodeQueue.pop();
printf("%d\t", tempNode->val);
if(tempNode->left!=NULL)
nodeQueue.push(tempNode->left);
if(tempNode->right!=NULL)
nodeQueue.push(tempNode->right);
}
}
/**
* @param:寻找最大的深度
*/
int BinaryTree :: findMaxDepth(TreeNode* temp)
{
static int depth = 0;
static int maxDepth = 0;
depth++;
if(temp->left!=NULL)
findMaxDepth(temp->left);
if(temp->right!=NULL)
findMaxDepth(temp->right);
maxDepth = max(maxDepth, depth);
depth--;
return maxDepth;
}
/* 另一种更好的解法
int BinaryTree :: findMaxDepth(TreeNode* temp)
{
if (temp == NULL)
return 0;
else
{
int ldepth = findMaxDepth(temp->left);
int rdepth = findMaxDepth(temp->right);
return ldepth > rdepth ? ldepth+1 : rdepth+1;
}
}
*/
int main()
{
vector<string> a = { "1", "2", "3", "4", "5", "6","7" };
BinaryTree* test = new BinaryTree(a);
test->printIntire();
printf("%d", test->findMaxDepth(test->head));
system("pause");
return 0;
}