The Wayback Machine - https://web.archive.org/web/20240818020059/https://www.geeksforgeeks.org/subtree-given-sum-binary-tree/
Open In App

Subtree with given sum in a Binary Tree

Last Updated : 11 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

You are given a binary tree and a given sum. The task is to check if there exists a subtree whose sum of all nodes is equal to the given sum.


Examples : 

// For above tree
Input : sum = 17
Output: “Yes”
// sum of all nodes of subtree {3, 5, 9} = 17
Input : sum = 11
Output: “No”
// no subtree with given sum exist

The idea is to traverse the tree in a Postorder fashion because here we have to think bottom-up. First, calculate the sum of the left subtree then the right subtree, and check if sum_left + sum_right + cur_node = sum is satisfying the condition that means any subtree with a given sum exists. Below is the recursive implementation of the algorithm. 
 

C++




// C++ program to find if there is a subtree with
// given sum
#include<bits/stdc++.h>
using namespace std;
  
/* A binary tree node has data, pointer to left child
   and a pointer to right child */
struct Node
{
    int data;
    struct Node* left, *right;
};
  
/* utility that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* newnode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right  = NULL;
    return (node);
}
  
// function to check if there exist any subtree with given sum
// cur_sum  --> sum of current subtree from ptr as root
// sum_left --> sum of left subtree from ptr as root
// sum_right --> sum of right subtree from ptr as root
bool sumSubtreeUtil(struct Node *ptr, int *cur_sum, int sum)
{
    // base condition
    if (ptr == NULL)
    {
        *cur_sum = 0;
        return false;
    }
  
    // Here first we go to left sub-tree, then right subtree
    // then first we calculate sum of all nodes of subtree
    // having ptr as root and assign it as cur_sum
    // cur_sum = sum_left + sum_right + ptr->data
    // after that we check if cur_sum == sum
    int sum_left = 0, sum_right = 0;
    return ( sumSubtreeUtil(ptr->left, ∑_left, sum) ||
             sumSubtreeUtil(ptr->right, ∑_right, sum) ||
        ((*cur_sum = sum_left + sum_right + ptr->data) == sum));
}
  
// Wrapper over sumSubtreeUtil()
bool sumSubtree(struct Node *root, int sum)
{
    // Initialize sum of subtree with root
    int cur_sum = 0;
  
    return sumSubtreeUtil(root, &cur;_sum, sum);
}
  
// driver program to run the case
int main()
{
    struct Node *root = newnode(8);
    root->left    = newnode(5);
    root->right   = newnode(4);
    root->left->left = newnode(9);
    root->left->right = newnode(7);
    root->left->right->left = newnode(1);
    root->left->right->right = newnode(12);
    root->left->right->right->right = newnode(2);
    root->right->right = newnode(11);
    root->right->right->left = newnode(3);
    int sum = 22;
  
    if (sumSubtree(root, sum))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}


Java




// Java program to find if there 
// is a subtree with given sum 
import java.util.*; 
class GFG
{
  
/* A binary tree node has data, 
pointer to left child and a
pointer to right child */
static class Node 
{ 
    int data; 
    Node left, right; 
}
  
static class INT
{
    int v;
    INT(int a)
    {
        v = a;
    }
}
  
/* utility that allocates a new
 node with the given data and 
 null left and right pointers. */
static Node newnode(int data) 
{ 
    Node node = new Node(); 
    node.data = data; 
    node.left = node.right = null; 
    return (node); 
} 
  
// function to check if there exist 
// any subtree with given sum 
// cur_sum -. sum of current subtree 
//            from ptr as root 
// sum_left -. sum of left subtree
//             from ptr as root 
// sum_right -. sum of right subtree
//              from ptr as root 
static boolean sumSubtreeUtil(Node ptr, 
                              INT cur_sum, 
                              int sum) 
{ 
    // base condition 
    if (ptr == null) 
    { 
        cur_sum = new INT(0); 
        return false; 
    } 
  
    // Here first we go to left 
    // sub-tree, then right subtree 
    // then first we calculate sum 
    // of all nodes of subtree having 
    // ptr as root and assign it as 
    // cur_sum. (cur_sum = sum_left + 
    // sum_right + ptr.data) after that
    // we check if cur_sum == sum 
    INT sum_left = new INT(0), 
        sum_right = new INT(0); 
    return (sumSubtreeUtil(ptr.left, sum_left, sum) || 
            sumSubtreeUtil(ptr.right, sum_right, sum) || 
        ((cur_sum.v = sum_left.v + 
                      sum_right.v + ptr.data) == sum)); 
} 
  
// Wrapper over sumSubtreeUtil() 
static boolean sumSubtree(Node root, int sum) 
{ 
    // Initialize sum of 
    // subtree with root 
    INT cur_sum = new INT( 0); 
  
    return sumSubtreeUtil(root, cur_sum, sum); 
} 
  
// Driver Code
public static void main(String args[])
{ 
    Node root = newnode(8); 
    root.left = newnode(5); 
    root.right = newnode(4); 
    root.left.left = newnode(9); 
    root.left.right = newnode(7); 
    root.left.right.left = newnode(1); 
    root.left.right.right = newnode(12); 
    root.left.right.right.right = newnode(2); 
    root.right.right = newnode(11); 
    root.right.right.left = newnode(3); 
    int sum = 22; 
  
    if (sumSubtree(root, sum)) 
        System.out.println( "Yes"); 
    else
        System.out.println( "No"); 
} 
}
  
// This code is contributed 
// by Arnab Kundu


Python3




# Python3 program to find if there is a 
# subtree with given sum 
  
# Binary Tree Node 
""" utility that allocates a newNode 
with the given key """
class newnode: 
  
    # Construct to create a newNode 
    def __init__(self, key): 
        self.data = key
        self.left = None
        self.right = None
  
# function to check if there exist any
# subtree with given sum 
# cur_sum -. sum of current subtree 
#            from ptr as root 
# sum_left -. sum of left subtree from 
#             ptr as root 
# sum_right -. sum of right subtree 
#              from ptr as root 
def sumSubtreeUtil(ptr,cur_sum,sum): 
  
    # base condition 
    if (ptr == None):
        cur_sum[0] = 0
        return False
  
    # Here first we go to left sub-tree, 
    # then right subtree then first we 
    # calculate sum of all nodes of subtree 
    # having ptr as root and assign it as cur_sum 
    # cur_sum = sum_left + sum_right + ptr.data 
    # after that we check if cur_sum == sum 
    sum_left, sum_right = [0], [0]
    x=sumSubtreeUtil(ptr.left, sum_left, sum)
    y=sumSubtreeUtil(ptr.right, sum_right, sum)
    cur_sum[0] = (sum_left[0] + 
                  sum_right[0] + ptr.data)
    return ((x or y)or (cur_sum[0] == sum))
  
# Wrapper over sumSubtreeUtil() 
def sumSubtree(root, sum): 
  
    # Initialize sum of subtree with root 
    cur_sum = [0] 
  
    return sumSubtreeUtil(root, cur_sum, sum) 
  
# Driver Code 
if __name__ == '__main__':
  
    root = newnode(8) 
    root.left = newnode(5) 
    root.right = newnode(4) 
    root.left.left = newnode(9) 
    root.left.right = newnode(7) 
    root.left.right.left = newnode(1) 
    root.left.right.right = newnode(12) 
    root.left.right.right.right = newnode(2) 
    root.right.right = newnode(11) 
    root.right.right.left = newnode(3) 
    sum = 22
  
    if (sumSubtree(root, sum)) :
        print("Yes" )
    else:
        print("No")
  
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#




using System;
  
// C# program to find if there 
// is a subtree with given sum 
public class GFG
{
  
/* A binary tree node has data, 
pointer to left child and a 
pointer to right child */
public class Node
{
    public int data;
    public Node left, right;
}
  
public class INT
{
    public int v;
    public INT(int a)
    {
        v = a;
    }
}
  
/* utility that allocates a new 
node with the given data and 
null left and right pointers. */
public static Node newnode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
}
  
// function to check if there exist 
// any subtree with given sum 
// cur_sum -. sum of current subtree 
//         from ptr as root 
// sum_left -. sum of left subtree 
//             from ptr as root 
// sum_right -. sum of right subtree 
//             from ptr as root 
public static bool sumSubtreeUtil(Node ptr, INT cur_sum, int sum)
{
    // base condition 
    if (ptr == null)
    {
        cur_sum = new INT(0);
        return false;
    }
  
    // Here first we go to left 
    // sub-tree, then right subtree 
    // then first we calculate sum 
    // of all nodes of subtree having 
    // ptr as root and assign it as 
    // cur_sum. (cur_sum = sum_left + 
    // sum_right + ptr.data) after that 
    // we check if cur_sum == sum 
    INT sum_left = new INT(0), sum_right = new INT(0);
    return (sumSubtreeUtil(ptr.left, sum_left, sum) 
            || sumSubtreeUtil(ptr.right, sum_right, sum) 
            || ((cur_sum.v = sum_left.v + sum_right.v + ptr.data) == sum));
}
  
// Wrapper over sumSubtreeUtil() 
public static bool sumSubtree(Node root, int sum)
{
    // Initialize sum of 
    // subtree with root 
    INT cur_sum = new INT(0);
  
    return sumSubtreeUtil(root, cur_sum, sum);
}
  
// Driver Code 
public static void Main(string[] args)
{
    Node root = newnode(8);
    root.left = newnode(5);
    root.right = newnode(4);
    root.left.left = newnode(9);
    root.left.right = newnode(7);
    root.left.right.left = newnode(1);
    root.left.right.right = newnode(12);
    root.left.right.right.right = newnode(2);
    root.right.right = newnode(11);
    root.right.right.left = newnode(3);
    int sum = 22;
  
    if (sumSubtree(root, sum))
    {
        Console.WriteLine("Yes");
    }
    else
    {
        Console.WriteLine("No");
    }
}
}
  
// This code is contributed by Shrikant13


Javascript




<script>
// javascript program to find if there 
// is a subtree with given sum 
  
    /*
     * A binary tree node has data, pointer to left child and a pointer to right
     * child
     */
     class Node {
        constructor(){
        this.data = 0;
        this.left = null;
        this.right = null;
        }
    }
  
     class INT {
  
        constructor(a) {
            this.v = a;
        }
    }
  
    /*
     * utility that allocates a new node with the given data and null left and right
     * pointers.
     */
    function newnode(data) {
        var node = new Node();
        node.data = data;
        node.left = node.right = null;
        return (node);
    }
  
    // function to check if there exist
    // any subtree with given sum
    // cur_sum -. sum of current subtree
    // from ptr as root
    // sum_left -. sum of left subtree
    // from ptr as root
    // sum_right -. sum of right subtree
    // from ptr as root
    function sumSubtreeUtil( ptr,  cur_sum , sum)
    {
      
        // base condition
        if (ptr == null) 
        {
            cur_sum = new INT(0);
            return false;
        }
  
        // Here first we go to left
        // sub-tree, then right subtree
        // then first we calculate sum
        // of all nodes of subtree having
        // ptr as root and assign it as
        // cur_sum. (cur_sum = sum_left +
        // sum_right + ptr.data) after that
        // we check if cur_sum == sum
        var sum_left = new INT(0), sum_right = new INT(0);
        return (sumSubtreeUtil(ptr.left, sum_left, sum) || sumSubtreeUtil(ptr.right, sum_right, sum)
                || ((cur_sum.v = sum_left.v + sum_right.v + ptr.data) == sum));
    }
  
    // Wrapper over sumSubtreeUtil()
    function sumSubtree( root, sum)
    {
      
        // Initialize sum of
        // subtree with root
        var cur_sum = new INT(0);
  
        return sumSubtreeUtil(root, cur_sum, sum);
    }
  
    // Driver Code
      
        var root = newnode(8);
        root.left = newnode(5);
        root.right = newnode(4);
        root.left.left = newnode(9);
        root.left.right = newnode(7);
        root.left.right.left = newnode(1);
        root.left.right.right = newnode(12);
        root.left.right.right.right = newnode(2);
        root.right.right = newnode(11);
        root.right.right.left = newnode(3);
        var sum = 22;
  
        if (sumSubtree(root, sum))
            document.write("Yes");
        else
            document.write("No");
  
// This code is contributed by Rajput-Ji
</script>


Output

Yes

Time Complexity: O(N), As we are visiting every node once.
Auxiliary space: O(h), Here h is the height of the tree and the extra space is used due to the recursion call stack.

 

Approach 2:- 

  •  Initialize a hash map mp to store the frequency of each sum encountered along the root-to-leaf paths of the binary tree.
  • Add a dummy entry in the map with sum 0 to handle the case where the root itself has the target sum.
  •  Initialize a stack st and push the root node onto it.
  • While the stack is not empty, pop the top node curr from the stack.
    • Update the sum as sum + curr->val.
    • Check if the difference sum – targetSum exists in the hash map. If it does, then return true.
    • Otherwise, add the current sum sum to the hash map with a frequency of 1.
    •  If the current node has a right child, push it onto the stack.
    • If the current node has a left child, push it onto the stack.
    • If the stack becomes empty, return false.

C++




#include <bits/stdc++.h>
using namespace std;
  
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x)
        : val(x)
        , left(NULL)
        , right(NULL)
    {
    }
};
  
bool hasTargetSum(TreeNode* root, int targetSum)
{
    unordered_map<int, int> mp;
    mp[0] = 1; // adding a dummy sum to handle the case
               // where root itself has the target sum
    int sum = 0;
    stack<TreeNode*> st;
    st.push(root);
    while (!st.empty()) {
        TreeNode* curr = st.top();
        st.pop();
        sum += curr->val;
        if (mp.find(sum - targetSum) != mp.end()) {
            return true;
        }
        mp[sum] = 1;
        if (curr->right) {
            st.push(curr->right);
        }
        if (curr->left) {
            st.push(curr->left);
        }
    }
    return false;
}
  
int main()
{
    /*
           5
         /   \
        4     8
       /     / \
      11    13  4
     /  \       \
    7    2       1
    */
    TreeNode* root = new TreeNode(5);
    root->left = new TreeNode(4);
    root->left->left = new TreeNode(11);
    root->left->left->left = new TreeNode(7);
    root->left->left->right = new TreeNode(2);
    root->right = new TreeNode(8);
    root->right->left = new TreeNode(13);
    root->right->right = new TreeNode(4);
    root->right->right->right = new TreeNode(1);
    int targetSum = 22;
    if (hasTargetSum(root, targetSum)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
    return 0;
}


Java




// Java implementation of above approach
import java.util.*;
  
// Create tree node
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}
  
class Solution {
    // Function to check the target
    public boolean hasTargetSum(TreeNode root,
                                int targetSum)
    {
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0,
                1); // adding a dummy sum to handle the case
                    // where root itself has the target sum
        int sum = 0;
        // Using stack to push node
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
  
        // Looping the stack
        while (!stack.empty()) {
            TreeNode curr = stack.pop();
            sum += curr.val;
            if (map.containsKey(
                    sum - targetSum)) { // checking target
                return true;
            }
            map.put(sum, 1);
            if (curr.right
                != null) { // calling the right node
                stack.push(curr.right);
            }
            if (curr.left
                != null) { // calling the left node
                stack.push(curr.left);
            }
        }
        return false;
    }
  
    public static void main(String[] args)
    {
  
        // Taken Tree
        /*
                 5
               /   \
              4     8
             /     / \
            11    13  4
           /  \       \
          7    2       1
          */
        // Input tree
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.left.left = new TreeNode(11);
        root.left.left.left = new TreeNode(7);
        root.left.left.right = new TreeNode(2);
        root.right = new TreeNode(8);
        root.right.left = new TreeNode(13);
        root.right.right = new TreeNode(4);
        root.right.right.right = new TreeNode(1);
        int targetSum = 22;
  
        Solution solution = new Solution();
        if (solution.hasTargetSum(root, targetSum)) {
            System.out.println("Yes");
        }
        else {
            System.out.println("No");
        }
    }
}


Python3




# Python implementation of above approach
from collections import defaultdict
  
# Create tree node
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
  
  # Function to check the target
def hasTargetSum(root, targetSum):
    mp = defaultdict(int)
    mp[0] = 1  # adding a dummy sum to handle the case
               # where root itself has the target sum
      
    stack = [root]   # Using stack to push node
    sum = 0
      
     # Looping the stack
    while stack:
        curr = stack.pop()
        sum += curr.val
        if sum - targetSum in mp:    # checking target
            return True
        mp[sum] = 1
        if curr.right:
            stack.append(curr.right)  # calling the right node
        if curr.left:
            stack.append(curr.left)   # calling the left node
    return False
  
"""
       5
     /   \
    4     8
   /     / \
  11    13  4
 /  \       \
7    2       1
"""
  
# Driver code
  
root = TreeNode(5)
root.left = TreeNode(4)
root.left.left = TreeNode(11)
root.left.left.left = TreeNode(7)
root.left.left.right = TreeNode(2)
root.right = TreeNode(8)
root.right.left = TreeNode(13)
root.right.right = TreeNode(4)
root.right.right.right = TreeNode(1)
targetSum = 22
if hasTargetSum(root, targetSum):
    print("Yes")
else:
    print("No")


C#




using System;
using System.Collections.Generic;
  
public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int x) { val = x; }
}
  
public class Solution {
    public bool HasTargetSum(TreeNode root, int targetSum)
    {
        Dictionary<int, int> mp
            = new Dictionary<int, int>();
        mp[0] = 1; // adding a dummy sum to handle the case
                   // where root itself has the target sum
        int sum = 0;
        Stack<TreeNode> st = new Stack<TreeNode>();
        st.Push(root);
        while (st.Count != 0) {
            TreeNode curr = st.Pop();
            sum += curr.val;
            if (mp.ContainsKey(
                    sum - targetSum)) { // check if the
                                        // difference exists
                                        // in the dictionary
                return true;
            }
            mp[sum] = 1; // add the sum to the dictionary
            if (curr.right != null) {
                st.Push(
                    curr.right); // add the right child to
                                 // the stack if it exists
            }
            if (curr.left != null) {
                st.Push(
                    curr.left); // add the left child to the
                                // stack if it exists
            }
        }
        return false;
    }
}
  
public class Program {
    static void Main(string[] args)
    {
        /*
               5
             /   \
            4     8
           /     / \
          11    13  4
         /  \       \
        7    2       1
        */
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.left.left = new TreeNode(11);
        root.left.left.left = new TreeNode(7);
        root.left.left.right = new TreeNode(2);
        root.right = new TreeNode(8);
        root.right.left = new TreeNode(13);
        root.right.right = new TreeNode(4);
        root.right.right.right = new TreeNode(1);
        int targetSum = 22;
        Solution sol = new Solution();
        if (sol.HasTargetSum(
                root,
                targetSum)) { // check if the target sum
                              // exists in the tree
            Console.WriteLine("Yes");
        }
        else {
            Console.WriteLine("No");
        }
    }
}


Javascript




// Definition for a binary tree node.
function TreeNode(val) {
    this.val = val;
    this.left = this.right = null;
}
  
function hasTargetSum(root, targetSum) {
    const map = new Map();
    map.set(0, 1); // adding a dummy sum to handle the case
    // where root itself has the target sum
    let sum = 0;
    const stack = [];
    stack.push(root);
    while (stack.length > 0) {
        const curr = stack.pop();
        sum += curr.val;
        if (map.has(sum - targetSum)) {
            return true;
        }
        map.set(sum, 1);
        if (curr.right) {
            stack.push(curr.right);
        }
        if (curr.left) {
            stack.push(curr.left);
        }
    }
    return false;
}
/*
5
/
4 8
/ /
11 13 4
/ \
7 2 1
*/
const root = new TreeNode(5);
root.left = new TreeNode(4);
root.left.left = new TreeNode(11);
root.left.left.left = new TreeNode(7);
root.left.left.right = new TreeNode(2);
root.right = new TreeNode(8);
root.right.left = new TreeNode(13);
root.right.right = new TreeNode(4);
root.right.right.right = new TreeNode(1);
  
const targetSum = 22;
if (hasTargetSum(root, targetSum)) {
    console.log("Yes"); // expected output: "Yes"
} else {
    console.log("No"); // expected output: "No"
}
// This code is contributed by sarojmcy2e


Output

Yes

Time complexity : – O(N)
Auxiliary Space :- O(N)



Previous Article
Next Article

Similar Reads

Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Check if a Binary tree is Subtree of another Binary tree | Set 3
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree-T Tree-S 1 3 / \ / 2
15 min read
Check if a binary tree is subtree of another binary tree | Set 2
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.For example, in the following case, Tree1 i
15+ min read
Check if a Binary Tree is subtree of another binary tree | Set 1
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree S 10 / \ 4 6 \ 30 Tr
11 min read
Count of nodes in given N-ary tree such that their subtree is a Binary Tree
Given an N-ary tree root, the task is to find the count of nodes such that their subtree is a binary tree. Example: Input: Tree in the image below Output: 11Explanation: The nodes such that there subtree is a binary tree are {2, 8, 10, 6, 7, 3, 1, 9, 5, 11, 12}. Input: Tree in the image below Output: 9 Approach: The given problem can be solved by u
11 min read
Most Frequent Subtree Sum from a given Binary Tree
Given a Binary Tree, the task is to find the most frequent subtree sum that can be obtained by considering every node of the given tree as the root of the subtree. If more than one such sums exist, then print all of them. Examples: Input: 5 / \ 2 -4 Output: 2 -4 3Explanation:The sum of nodes considering 5 as the root of subtree is 5 + 2 - 4 = 3.The
13 min read
Sum of subtree depths for every node of a given Binary Tree
Given a binary tree consisting of N nodes, the task is to find the sum of depths of all subtree nodes in a given binary tree. Examples: Input: Output: 26Explanation: The leaf nodes having value 8, 9, 5, 6, and 7 have the sum of subtree depths equal to 0.Node 4 has a total of 2 nodes in its subtree, both in the same level. Therefore, sum of subtree
15+ min read
Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
Given a binary tree, change the value in each node to sum of all the values in the nodes in the right subtree including its own. Examples: Input : 1 / \ 2 3 Output : 4 / \ 2 3 Input : 1 / \ 2 3 / \ \ 4 5 6 Output : 10 / \ 7 9 / \ \ 4 5 6 Approach : The idea is to traverse the given binary tree in bottom up manner. Recursively compute the sum of nod
7 min read
Change a Binary Tree so that every node stores sum of all nodes in left subtree
Given a Binary Tree, change the value in each node to sum of all the values in the nodes in the left subtree including its own. Examples: Input : 1 / \ 2 3 Output : 3 / \ 2 3 Input 1 / \ 2 3 / \ \ 4 5 6 Output: 12 / \ 6 3 / \ \ 4 5 6 We strongly recommend you to minimize your browser and try this yourself first.The idea is to traverse the given tre
8 min read
Find the largest BST subtree in a given Binary Tree | Set 3
Largest BST in a Binary Tree | Set 3Method 3 (Shorter, Smarter and More Efficient) In this section, a different O(n) solution is discussed. This solution is simpler than the solutions discussed in Set-1 and Set-2 and works in O(n) time. In this method, we do not need to check explicitly if the binary tree is BST. A Tree is BST if the following is t
8 min read
Find the largest Complete Subtree in a given Binary Tree
Given a Binary Tree, the task is to find the size of largest Complete sub-tree in the given Binary Tree. Complete Binary Tree - A Binary tree is Complete Binary Tree if all levels are completely filled except possibly the last level and the last level has all keys as left as possible. Note: All Perfect Binary Trees are Complete Binary tree but reve
15+ min read
Maximum average of subtree values in a given Binary Tree
Given a Binary Tree consisting of N nodes, the task to find the maximum average of values of nodes of any subtree. Examples: Input: 5 / \ 3 8 Output: 8Explanation:Average of values of subtree of node 5 = (5 + 3 + 8) / 3 = 5.33Average of values of subtree of node 3 = 3 / 1 = 3Average of values of subtree of node 8 = 8 / 1 = 8. Input: 20 / \ 12 18 /
9 min read
Check if the given Binary Tree have a Subtree with equal no of 1's and 0's
Given a Binary Tree having data at nodes as either 0's or 1's. The task is to find out whether there exists a subtree having an equal number of 1's and 0's. Examples: Input : Output : True There are two subtrees present in the above tree where the number of 1's is equal to the number of 0's. Input : Output : False There is no such subtree present w
10 min read
Find the largest Perfect Subtree in a given Binary Tree
Given a Binary Tree, the task is to find the size of largest Perfect sub-tree in the given Binary Tree. Perfect Binary Tree - A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all leaves are at the same level. Examples: Input: 1 / \ 2 3 / \ / 4 5 6 Output: Size : 3 Inorder Traversal : 4 2 5 The following sub-tre
12 min read
Print all nodes present in the subtree of a given node of a Binary Tree
Given two arrays Node_ID[] and Parent_ID[]., construct a binary tree where value of ith node is equal to Node_ID[i] and parent of ith node is Parent_ID[i]. Given a node X, the task is to print node values of the tree rooted at X. Examples: Input: Node_ID[]= [11, 48, 100, 5], Parent_ID[] = [48, 0, 5, 48], X = 5Output: [5, 100]Explanation: The tree c
11 min read
Trim given Binary Tree for any subtree containing only 0s
Given a Binary tree, the task is to trim this tree for any subtree containing only 0s. Examples: Input: 1 \ 0 / \ 0 1 Output: 1 \ 0 \ 1 Explanation: The subtree shown as bold below does not contain any 1. Hence it can be trimmed. 1 \ 0 / \ 0 1 Input: 1 / \ 1 0 / \ / \ 1 1 0 1 / 0 Output: 1 / \ 1 0 / \ \ 1 1 1 Input: 1 / \ 0 1 / \ / \ 0 0 0 1 Output
7 min read
Count of nodes with average of left subtree at least K in a given Binary Tree
Given a binary tree and a number K, the task is to count the number of nodes having the average of the values in their left subtree greater than or equal to K. Examples: Input : K=5Tree: 2 / \ 5 4 / \ / \ 5 6 6 2 \ / 5 4Output: 3Explanation: 2 -------- level 0 / \ 5 4 -------- level 1 / \ / \ 5 6 6 2 -------- level 2 \ / 5 4 -------- level 3 Left l
15+ min read
Largest subtree sum for each vertex of given N-ary Tree
Given an N-array tree of N nodes, rooted at 1, with edges in the form {u, v}, and an array values[] consisting of N integers. Each vertex i has an integer value denoted by values[i]. The task is to find the largest Subtree Sum possible for each vertex i by adding its value to a non-empty subset of its child vertices. Examples: Input: Edges[][] = {{
10 min read
Duplicate subtree in Binary Tree | SET 2
Given a binary tree, the task is to check whether the binary tree contains a duplicate sub-tree of size two or more. Input: A / \ B C / \ \ D E B / \ D E Output: Yes B / \ D E is the duplicate sub-tree. Input: A / \ B C / \ D E Output: No Approach: A DFS based approach has been discussed here. A queue can be used to traverse the tree in a bfs manne
8 min read
Find the maximum element of every subtree of a Binary Tree
Given a Binary Tree, find the maximum element of every subtree of it. Examples :Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : [4, 5, 5, 7, 6, 7, 7] Explanation: The maximum element of the subtree rooted at node 4 is 4. The maximum element of the subtree rooted at node 2 is 5. The maximum element of the subtree rooted at node 5 is 5. The maximum elemen
15+ min read
Find largest subtree sum in a tree
Given a binary tree, task is to find subtree with maximum sum in tree. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 28 As all the tree elements are positive, the largest subtree sum is equal to sum of all tree elements. Input : 1 / \ -2 3 / \ / \ 4 5 -6 2 Output : 7 Subtree with largest sum is : -2 / \ 4 5 Also, entire tree sum is also 7.Re
15+ min read
Find the Kth node in the DFS traversal of a given subtree in a Tree
Given a tree with N nodes, and two integers K and V. The task is to find the Kth node in the DFS traversal of the vertex V.Consider the below Tree: DFS of node number 1 is [1, 2, 3, 5, 6, 8, 7, 9, 4]. DFS of node number 3 is [3, 5, 6, 8, 7, 9] DFS of node number 7 is [7, 9] DFS of node number 9 is [9]. Print "-1" if the numbers in the DFS of vertex
10 min read
Count of distinct colors in a subtree of a Colored Tree with given min frequency for Q queries
Given a N-ary tree with some colour associated with every node and Q queries. Each query contains two integers A and X. The task is to count all distinct colors in a subtree rooted at A, having frequency of colors greater than or equal to X in that subtree.Examples: Input: Tree: 1(1) / \ / \ 2(2) 5(3) / \ / | \ / \ / | \ 3(2) 4(3) 6(2) 7(3) 8(3) qu
15+ min read
Find GCD of each subtree of a given node in an N-ary Tree for Q queries
Given an N-ary Tree containing N nodes, values associated with each node and Q queries, where each query contains a single node. The task is to find the GCD of values of all the nodes present in the subtree (including itself). Example: Tree: 1(2) / \ / \ 2(3) 3(4) / \ / \ 4(8) 5(16) query[]: {2, 3, 1} Output: {3, 4, 1} Explanation: For query 1: GCD
10 min read
Count of nodes in a given N-ary tree having distance to all leaf nodes equal in their subtree
Given an N-ary tree root, the task is to find the number of non-leaf nodes in the tree such that all the leaf nodes in the subtree of the current node are at an equal distance from the current node. Example: Input: Tree in the below imageOutput: 4Explanation: The nodes {10, 3, 2, 4} have the distance between them and all the leaf nodes in their sub
11 min read
Find MEX of every subtree in given Tree
Given a Generic Tree consisting of N nodes numbered from 0 to N - 1 which is rooted at node 0 and an array val[] such that the value at each node is represented by val[i], the task for each node is to find the value of MEX of its subtree. The MEX value of node V is defined as the smallest missing positive number in a tree rooted at node V. Examples
12 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Convert a Binary Tree into its Mirror Tree (Invert Binary Tree)
Given a binary tree, the task is to convert the binary tree into its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Recommended PracticeMirror TreeTry It!The idea is to traverse recursively and swap the right and left subtrees after traversing the subtrees. Follow
15+ min read
Check whether a given binary tree is skewed binary tree or not?
Given a Binary Tree check whether it is skewed binary tree or not. A skewed tree is a tree where each node has only one child node or none. Examples: Input : 5 / 4 \ 3 / 2 Output : Yes Input : 5 / 4 \ 3 / \ 2 4 Output : No The idea is to check if a node has two children. If node has two children return false, else recursively compute whether subtre
13 min read
Even size subtree in n-ary tree
Given an n-ary tree of n vertices and n-1 edges. The tree is given in the form of adjacency list. Find number of subtrees of even size in given tree. Examples: Input : 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 Output : 2 Subtree rooted at 1 and 3 are of even size. Input : 1 / \ 2 3 / | \ \ 4 5 6 7 / | \ 8 9 10 Output : 3 Subtree rooted at 1, 3 and 5 are of eve
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg