C++ 最大包含相同数量 1 和 0 的子树
给定一棵二叉树。现在我们的任务是找到包含相同数量的 1 和 0 的最大子树;树只包含 0 和 1。
查找解决方案的方法
在这种方法中,我们将把所有值为 0 的节点替换为 -1。这样做将使我们的程序更简单,因为我们现在需要找到总和等于 0 的最大子树。
示例
上述方法的 C++ 代码
#include <iostream>
using namespace std;
int maxi = -1;
struct node { // structure of our tree node
int data;
struct node *right, *left;
};
struct node* newnode(int key){// To create a new node
struct node* temp = new node;
temp->data = key;
temp->right = NULL;
temp->left = NULL;
return temp;
}
void inorder(struct node* root){ // traversing the tree(not used)
if (root == NULL)
return;
inorder(root->left);
cout << root->data << endl;
inorder(root->right);
}
// Function to return the maximum size of
// the sub-tree having an equal number of 0's and 1's
int calculatingmax(struct node* root){
int a = 0, b = 0;
if (root == NULL)
return 0;
a = calculatingmax(root->right); // right subtree
a = a + 1; // including parent
b = calculatingmax(root->left); // left subtree
a = b + a; // number of nodes at current subtree
if (root->data == 0) // if the sum of whole subtree is 0
// If the total size exceeds
// the current max
if (a >= maxi)
maxi = a;
return a;
}
int calc_sum(struct node* root){ // updating the values at each node
if (root != NULL){
if (root->data == 0){
root->data = -1;
}
}
int a = 0, b = 0;
// If left child exists
if (root->left != NULL)
a = calc_sum(root->left);
// If right child exists
if (root->right != NULL)
b = calc_sum(root->right);
root->data += (a + b);
return root->data;
}
// Driver code
int main(){
struct node* root = newnode(1);
root->right = newnode(0);
root->right->right = newnode(1);
root->right->right->right = newnode(1);
root->left = newnode(0);
root->left->left = newnode(1);
root->left->left->left = newnode(1);
root->left->right = newnode(0);
root->left->right->left = newnode(1);
root->left->right->left->left = newnode(1);
root->left->right->right = newnode(0);
root->left->right->right->left = newnode(0);
root->left->right->right->left->left = newnode(1);
calc_sum(root);
calculatingmax(root);
// cout << "h";
cout << maxi;
return 0;
}输出
6
上述代码的解释
在上述方法中,我们将所有值为 0 的节点更新为 -1,然后我们将问题简化为找到总和等于 0 的最大子树,现在在更新过程中,我们还更新所有节点,这些节点的值充满了以该节点为根的子树的重要性,现在我们使用第二个函数来计算和检查每个值为 0 的节点,然后找到该树中存在的最大节点数。
结论
在本教程中,我们解决了一个问题,即查找包含相同数量的 1 和 0 的最大子树。我们还学习了此问题的 C++ 程序以及解决此问题的完整方法(普通方法)。我们可以使用其他语言(如 C、Java、Python 和其他语言)编写相同的程序。我们希望您觉得本教程有所帮助。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP