C++ 中的二叉樹剪枝
假設我們有兩個二叉樹的頭節點 root,其中每個節點的值是 0 或 1。我們必須找到同一棵樹,其中所有不包含 1 的子樹已被刪除。所以如果這棵樹像 -

為解決這個問題,我們將遵循以下步驟:
定義一個遞迴方法 solve(),它將獲取節點,該方法如下:
如果節點為 null,則返回 null
節點的左節點 := solve(節點的左節點)
節點的右節點 := 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, ]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP