[LeetCode] Binary Tree Pruning

814. Binary Tree Pruning

Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.

A subtree of a node node is node plus every node that is a descendant of node.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for a binary tree node.
* 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) {}
* };
*/
class Solution {
bool helper(TreeNode* node) {
if(!node) return false;
if(!helper(node->left)) node->left = nullptr;
if(!helper(node->right)) node->right = nullptr;
return node->left != nullptr or node->right != nullptr or node->val == 1;
}
public:
TreeNode* pruneTree(TreeNode* root) {
return helper(root) ? root : nullptr;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/21/PS/LeetCode/binary-tree-pruning/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.