Repository navigation
Expand file tree
/
Copy pathmaxPathSum.cpp
More file actions
84 lines (59 loc) · 1.56 KB
/
Copy pathmaxPathSum.cpp
File metadata and controls
84 lines (59 loc) · 1.56 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
#include <iostream>
#include <queue>
using namespace std;
/*
| Question: Find the Maximum Pat Sum in a Binary Tree
|
| Approach#1: Perform a traversal(similar to the way you cal)
| calculate the height) and pick the largest number
| Add the current value to the sum and return in.
|
|
*/
/*
Nice work!
*/
// Structure of a node
struct node{
node * left = NULL;
node * right = NULL;
node(node * l, node * r, int dat){
left = l;
right = r;
data = dat;
}
int data;
};
// Purpose: To calculate the max sum of a path in a tree
int findMaxSum(node * root){
if(!root) return 0;
return root->data + max(findMaxSum(root->left), findMaxSum(root->right));
}
// Purpose: to print the tree
void printByLevel(queue <node*> myq){
if(myq.empty()) return;
queue<node*> next;
while(!myq.empty()){
node * temp = myq.front();
myq.pop();
cout<<temp->data<<" ";
if(temp->left) next.push(temp->left);
if(temp->right) next.push(temp->right);
}
cout<<endl;
printByLevel(next);
}
using namespace std;
int main() {
queue<node*> myq;
node * twnt = new node(NULL,NULL,20);
node * thir5 = new node(NULL,NULL, 35);
node * fourty = new node(thir5,NULL,40);
node * thirty = new node(twnt,fourty,30);
node * eighty = new node(NULL,NULL,80);
node * fifty = new node(thirty,eighty,50);
myq.push(fifty);
//printByLevel(myq);
cout<<findMaxSum(fifty)<<endl;
return 0;
}