추가로 모든 노드의 값이 0 또는 1인 이진 트리의 헤드 노드 루트가 있다고 가정합니다. 1을 포함하지 않는 모든 하위 트리가 삭제된 동일한 트리를 찾아야 합니다. 트리가 다음과 같다면 -

이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
재귀 메서드 solve()를 정의하면 노드가 사용됩니다. 방법은 다음과 같습니다 -
-
노드가 null이면 null을 반환합니다.
-
노드 왼쪽 :=해결(노드 왼쪽)
-
노드 오른쪽 :=solve(노드 오른쪽)
-
노드의 왼쪽이 null이고 노드의 오른쪽도 null이고 노드 값이 0이면 null을 반환합니다.
-
반환 노드
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
예시
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = NULL;
right = NULL;
}
};
void insert(TreeNode **root, int val){
queue<TreeNode*> q;
q.push(*root);
while(q.size()){
TreeNode *temp = q.front();
q.pop();
if(!temp->left){
temp->left = new TreeNode(val);
return;
}else{
q.push(temp->left);
}
if(!temp->right){
temp->right = new TreeNode(val);
return;
}else{
q.push(temp->right);
}
}
}
TreeNode *make_tree(vector<int> v){
TreeNode *root = new TreeNode(v[0]);
for(int i = 1; i<v.size(); i++){
insert(&root, v[i]);
}
return root;
}
void tree_level_trav(TreeNode*root){
if (root == NULL) return;
cout << "[";
queue<TreeNode *> q;
TreeNode *curr;
q.push(root);
q.push(NULL);
while (q.size() > 1) {
curr = q.front();
q.pop();
if (curr == NULL){
q.push(NULL);
} else {
if(curr->left)
q.push(curr->left);
if(curr->right)
q.push(curr->right);
if(curr == NULL){
cout << "null" << ", ";
}else{
cout << curr->val << ", ";
}
}
}
cout << "]"<<endl;
}
class Solution {
public:
TreeNode* pruneTree(TreeNode* node) {
if(!node)return NULL;
node->left = pruneTree(node->left);
node->right = pruneTree(node->right);
if(!node->left && !node->right && !node->val){
return NULL;
}
return node;
}
};
main(){
vector<int> v = {1,1,0,1,1,0,1,0};
TreeNode *root = make_tree(v);
Solution ob;
tree_level_trav(ob.pruneTree(root));
} 입력
[1,1,0,1,1,0,1,0]
출력
[1, 1, 0, 1, 1, 1, ]