将给定的二叉树转换为在C ++上具有逻辑AND属性的树

在本教程中,我们将讨论将给定的Binary树转换为具有Logical AND属性的树的程序。

为此,我们将提供一个二叉树。我们的任务是将其转换为具有逻辑AND属性的树,这意味着一个节点具有其子节点的AND操作值。请注意,每个节点的值可以为零或一。

示例

#include<bits/stdc++.h>
using namespace std;
//二叉树的节点结构
struct Node{
   int data;
   struct Node* left;
   struct Node* right;
};
//创建一个新节点
struct Node* newNode(int key){
   struct Node* node = new Node;
   node->data= key;
   node->left = node->right = NULL;
   return node;
}
//转换带有以下节点的树
//逻辑AND运算
void transform_tree(Node *root){
   if (root == NULL)
      return;
   //移动到第一个左节点
   transform_tree(root->left);
   //移动到第一个右节点
   transform_tree(root->right);
   if (root->left != NULL && root->right != NULL)
      root->data = (root->left->data) &
   (root->right->data);
}
//打印顺序遍历
void print_tree(Node* root){
   if (root == NULL)
      return;
   print_tree(root->left);
   printf("%d ", root->data);
   print_tree(root->right);
}
int main(){
   Node *root=newNode(0);
   root->left=newNode(1);
   root->right=newNode(0);
   root->left->left=newNode(0);
   root->left->right=newNode(1);
   root->right->left=newNode(1);
   root->right->right=newNode(1);
   printf("Before conversion :\n");
   print_tree(root);
   transform_tree(root);
   printf("\nAfter conversion :\n");
   print_tree(root);
   return 0;
}

输出结果

Before conversion :
0 1 1 0 1 0 1
After conversion :
0 0 1 0 1 1 1