Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

แปลง Binary Tree ให้เป็นต้นไม้ที่มีคุณสมบัติ Logical AND ใน C++

คำอธิบายปัญหา

ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมแปลง binary tree ที่กำหนดให้เป็นต้นไม้ที่มีคุณสมบัติ Logical AND

สำหรับนี้ เราจะได้รับ binary tree งานของเราคือแปลงมันเป็นต้นไม้ที่มีคุณสมบัติ Logical AND หมายถึง โหนดหนึ่งมีค่าเท่ากับผลของการ AND ระหว่างโหนดลูกของมัน โปรดทราบว่าทุกโหนดสามารถมีค่าได้แค่ 0 หรือ 1 เท่านั้น

ตัวอย่างโค้ด

#include<bits/stdc++.h> using namespace std; //node structure of binary tree struct Node{    int data;    struct Node* left;    struct Node* right; }; //creation of a new node struct Node* newNode(int key){    struct Node* node = new Node;    node->data= key;    node->left = node->right = NULL;    return node; } //converting the tree with nodes following //logical AND operation void transform_tree(Node *root){    if (root == NULL)       return;    //moving to first left node    transform_tree(root->left);    //moving to first right node    transform_tree(root->right);    if (root->left != NULL && root->right != NULL)       root->data = (root->left->data) &    (root->right->data); } //printing the inorder traversal 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