-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreePruning.cpp
More file actions
55 lines (46 loc) · 986 Bytes
/
BinaryTreePruning.cpp
File metadata and controls
55 lines (46 loc) · 986 Bytes
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
#include<iostream>
#include<stack>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
TreeNode* pruneTree(TreeNode* root) {
// std::stack<TreeNode*> dfStack;
int total = dfs(root);
if(total == 0) {
return;
}
return root;
}
// Left int: total node value
// Right int: 0 - left, 1 - right, 2 - root
int dfs(TreeNode* currNode) {
int val = currNode->val;
int temp;
if(currNode->left != nullptr) {
temp = dfs(currNode->left);
if(temp == 0) {
currNode->left = nullptr;
}
else {
val += temp;
}
}
if(currNode->right != nullptr) {
temp = dfs(currNode->right);
if(temp == 0) {
currNode->right = nullptr;
}
else {
val += temp;
}
}
return val;
}
int main() {
return 0;
}