Question:
How to check for children sum property in a Binary Tree using C++

Summary

This C++ code defines a class called Solution, which contains methods to determine if the value of each node in a tree adds up to the total of all of its child nodes.


Solution

/*Complete the function below


struct Node

{

    int data;

    struct Node* left;

    struct Node* right;

    

    Node(int x){80

        data = x;

        left = right = NULL;

    }

};

*/


class Solution{

    public:

    //Function to check whether all nodes of a tree have the value 

    //equal to the sum of their child nodes.

    int ans=1;

    

    int solve(Node *root)

    {

        

        if(root==nullptr)   

            return 0;

        if(root->left==nullptr && root->right==nullptr)

            return root->data;

        int temp=(solve(root->left)+solve(root->right));

        if(root->data!=temp)

            ans=0;

        return root->data;

        

        

        

    }

    int isSumProperty(Node *root)

    {

     // Add your code here

        solve(root);

        return ans;

        

        

    }

};


Explanation

  • A binary tree node is defined by this structure.

  • In addition to pointers to its left and right child nodes, each node has an integer data set.

  • Ans, a public member variable, has a value of 1 by default. This variable keeps track of whether the condition is met across the board for the tree.

  • It has a private method called solve that is called recursively to examine the sum property by going through the tree.


Answered by:> >vnsahu1331

Credit:> >GeekforGeeks


Suggested blogs:

>How to detect whether the linked list has a loop using Java

>How to determine the number of valid groupings for a string using Java

>How to mock a constant value in Python?

>Creating a pivot table by 6 month interval rather than year

>How to Install mariaDB client efficiently inside docker?

>Can I call an API to find out the random seed in Python `hash()` function?

>How remove residual lines after merge two regions using Geopandas in python?


Submit
0 Answers

What Our Clients Say About Us

Client satisfaction is our ultimate goal. Here are some kind words of our precious clients they have used to express their satisfaction with our service.

Why Choose Us ?

We endow businesses with flexible engagement models based on their unique needs. Our strength lies in state-of-the-art technology and affordable consulting services. Try us for fast POCs, full-fledged applications, or technology consulting. Always available for your service.