-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path814.cpp
29 lines (29 loc) · 847 Bytes
/
814.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution { // Runtime: 4 ms, faster than 91.95% of C++ online submissions
// for Binary Tree Pruning.
public:
TreeNode *pruneTree(TreeNode *root) {
function<bool(TreeNode *)> postorder = [&postorder](TreeNode *node) {
if (!node)
return true;
auto removeThis = node->val == 0;
auto removeL = postorder(node->left);
if (removeL)
node->left = nullptr;
auto removeR = postorder(node->right);
if (removeR)
node->right = nullptr;
removeThis = removeThis and removeL and removeR;
return removeThis;
};
return postorder(root) ? nullptr : root;
}
};