-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxDistanceOfTree.cpp
More file actions
86 lines (74 loc) · 2.11 KB
/
MaxDistanceOfTree.cpp
File metadata and controls
86 lines (74 loc) · 2.11 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
#include <iostream>
#include "TreeUtil.h"
using namespace std;
int maxDistance(BinaryTree* root, int& deep) {
if(!root) {//null node
deep = 0;
return 0;
}
if(!root->left && !root->right) {// leaf node
deep = 0;
return 0;
}
int leftDeep = 0;
int rightDeep = 0;
int leftDis = 0;
int rightDis = 0;
if(root->left) {
leftDis = maxDistance(root->left, leftDeep);
leftDeep++;
}
if(root->right) {
rightDis = maxDistance(root->right, rightDeep);
rightDeep++;
}
deep = max(leftDeep, rightDeep);
int dis = max( max(leftDis, rightDis), leftDeep + rightDeep);
return dis;
}
int main() {
int deep, dis;
{
string treeDesc = "1|"
"2,3|"
"4,5,6,7|";
BinaryTree* root = TreeUtil::buildTree(treeDesc);
dis = maxDistance(root, deep);
cout << "max distance:" << dis << endl;
cout << "deep:" << deep << endl;
TreeUtil::layerTraverse(root);
}
{
string treeDesc = "1|"
"2,#|"
"4,#,#,#|";
BinaryTree* root = TreeUtil::buildTree(treeDesc);
dis = maxDistance(root, deep);
cout << "max distance:" << dis << endl;
cout << "deep:" << deep << endl;
TreeUtil::layerTraverse(root);
}
{
string treeDesc = "1|"
"#,3|"
"#,#,#,7|";
BinaryTree* root = TreeUtil::buildTree(treeDesc);
dis = maxDistance(root, deep);
cout << "max distance:" << dis << endl;
cout << "deep:" << deep << endl;
TreeUtil::layerTraverse(root);
}
{
string treeDesc = "1|"
"2,3|"
"4,5,#,#|"
"7,8,9,#,#,#,#,#|"
"#,#,#,8,9,#,#,#,#,#|";
BinaryTree* root = TreeUtil::buildTree(treeDesc);
dis = maxDistance(root, deep);
cout << "max distance:" << dis << endl;
cout << "deep:" << deep << endl;
TreeUtil::layerTraverse(root);
}
return 0;
}