08(Aug) Sum Tree

08. Sum Tree

The problem can be found at the following link: Question Link

Problem Description

Given a Binary Tree, check whether it is a Sum Tree or not. A Sum Tree is a Binary Tree where the value of a node is equal to the sum of the nodes present in its left subtree and right subtree. An empty tree is also considered a Sum Tree as the sum of an empty tree can be considered to be 0. A leaf node is also considered a Sum Tree.

Example:

Input:

    3
  /   \
 1     2

Output:

true

Explanation: The sum of the left subtree and right subtree is 1 + 2 = 3, which is the value of the root node. Therefore, the given binary tree is a Sum Tree.

Input:

          10
        /    \
      20      30
    /   \
   10    10

Output:

Explanation: The given tree is not a Sum Tree. For the root node, the sum of elements in the left subtree is 40 and the sum of elements in the right subtree is 30. The root element is 10, which is not equal to 30 + 40.

My Approach

  1. Leaf Node Check:

    • Define a helper function isLeaf to check if a node is a leaf node (i.e., it has no children).

  2. Sum Tree Check:

    • Define a recursive helper function checkSumTree that checks whether a given tree is a Sum Tree. This function calculates the sum of the nodes in the left and right subtrees and verifies if the current node's value equals this sum.

  3. Main Function:

    • The main function isSumTree uses the checkSumTree helper to determine if the entire tree is a Sum Tree.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), where n is the number of nodes in the binary tree. Each node is visited once in a post-order traversal.

  • Expected Auxiliary Space Complexity: O(h), where h is the height of the binary tree. This space is used by the call stack during recursion.

Code (C++)

Code (Java)

Code (Python)

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated