Open In App

Tilt of Binary Tree

Last Updated : 15 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary tree, return the tilt of the whole tree. The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null nodes are assigned tilt to be zero. Therefore, tilt of the whole tree is defined as the sum of all nodes’ tilt.

Examples: 

Input :
1
/ \
2 3

Output : 1
Explanation:Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1
Input :
4
/ \
2 9
/ \ \
3 5 7
Output : 15
Explanation:Tilt of node 3 : 0
Tilt of node 5 : 0
Tilt of node 7 : 0
Tilt of node 2 : |3-5| = 2
Tilt of node 9 : |0-7| = 7
Tilt of node 4 : |(3+5+2)-(9+7)| = 6
Tilt of binary tree : 0 + 0 + 0 + 2 + 7 + 6 = 15
Recommended Practice

Naive Approach (Finding Sum at every Node): The idea is to find the sum of the left and the right subtree at every node and keep adding their absolute differences. Find the sum of the left subtree and right subtree using the findSum function and take its absolute difference and at the end return the sum of absolute diff and leftSubtree tilt and rightSubtree tilt which will be the total tilt of the tree.

Implementation:

C++




// CPP Program to find Tilt of Binary Tree
 
#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 val;
    struct Node *left, *right;
};
 
/* Recursive function to calculate Sum of
  values of subtree */
int findSum(Node* root)
{
    if (root == NULL)
        return 0;
    return root->val + findSum(root->left)
           + findSum(root->right);
}
 
/* Driver function to print Tilt of whole tree */
int Tilt(Node* root)
{
    if (root == NULL)
        return 0;
 
    int left = Tilt(root->left);
    int right = Tilt(root->right);
 
    return abs(findSum(root->left) - findSum(root->right))
           + left + right;
}
 
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->val = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Driver code
int main()
{
    /* Let us construct a Binary Tree
        4
       / \
      2   9
     / \   \
    3   5   7 */
 
    Node* root = NULL;
    root = newNode(4);
    root->left = newNode(2);
    root->right = newNode(9);
    root->left->left = newNode(3);
    root->left->right = newNode(8);
    root->right->right = newNode(7);
    cout << "The Tilt of whole tree is " << Tilt(root);
 
    return 0;
}


Java




// Java Program to find Tilt of Binary Tree
class Main {
 
    /* A binary tree node has data, a left child, and a right child */
    static class Node {
        int val;
        Node left, right;
 
        Node(int data) {
            val = data;
            left = right = null;
        }
    }
 
    /* Recursive function to calculate the sum of values in a subtree */
    static int findSum(Node root) {
        if (root == null)
            return 0;
        return root.val + findSum(root.left) + findSum(root.right);
    }
 
    /* Function to calculate the Tilt of the whole tree */
    static int Tilt(Node root) {
        if (root == null)
            return 0;
 
        int left = Tilt(root.left);
        int right = Tilt(root.right);
 
        return Math.abs(findSum(root.left) - findSum(root.right)) + left + right;
    }
 
    /* Helper function to create a new node with the given data */
    static Node newNode(int data) {
        Node temp = new Node(data);
        temp.left = temp.right = null;
        return temp;
    }
 
    // Driver code
    public static void main(String[] args) {
        /* Let us construct a Binary Tree
            4
           / \
          2   9
         / \   \
        3   5   7 */
 
        Node root = null;
        root = newNode(4);
        root.left = newNode(2);
        root.right = newNode(9);
        root.left.left = newNode(3);
        root.left.right = newNode(8);
        root.right.right = newNode(7);
        System.out.println("The Tilt of whole tree is " + Tilt(root));
    }
}
 
// This code is contributed by guptapratik


Python3




# Python Program to find Tilt of Binary Tree
 
# A binary tree node has data, a left child, and a right child
class Node:
    def __init__(self, data):
        self.val = data
        self.left = None
        self.right = None
 
# Recursive function to calculate the sum of values in a subtree
def findSum(root):
    if root is None:
        return 0
    return root.val + findSum(root.left) + findSum(root.right)
 
# Function to calculate the Tilt of the whole tree
def Tilt(root):
    if root is None:
        return 0
 
    left = Tilt(root.left)
    right = Tilt(root.right)
 
    return abs(findSum(root.left) - findSum(root.right)) + left + right
 
# Helper function to create a new node with the given data
def newNode(data):
    temp = Node(data)
    temp.left = temp.right = None
    return temp
 
# Driver code
if __name__ == "__main__":
    # Let us construct a Binary Tree
    #     4
    #    / \
    #   2   9
    #  / \   \
    # 3   5   7
 
    root = None
    root = newNode(4)
    root.left = newNode(2)
    root.right = newNode(9)
    root.left.left = newNode(3)
    root.left.right = newNode(8)
    root.right.right = newNode(7)
    print("The Tilt of whole tree is", Tilt(root))
 
# This code is contributed by guptapratik


C#




// C# Code
 
using System;
 
// C# Program to find Tilt of Binary Tree
class GFG
{
    // A binary tree node has data, a left child, and a right child
    class Node
    {
        public int val;
        public Node left, right;
 
        public Node(int data)
        {
            val = data;
            left = null;
            right = null;
        }
    }
 
    // Recursive function to calculate the sum of values in a subtree
    static int FindSum(Node root)
    {
        if (root == null)
            return 0;
        return root.val + FindSum(root.left) + FindSum(root.right);
    }
 
    // Function to calculate the Tilt of the whole tree
    static int Tilt(Node root)
    {
        if (root == null)
            return 0;
 
        int left = Tilt(root.left);
        int right = Tilt(root.right);
 
        return Math.Abs(FindSum(root.left) - FindSum(root.right)) + left + right;
    }
 
    // Helper function to create a new node with the given data
    static Node NewNode(int data)
    {
        Node temp = new Node(data);
        temp.left = temp.right = null;
        return temp;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        // Let us construct a Binary Tree
        //     4
        //    / \
        //   2   9
        //  / \   \
        // 3   5   7
 
        Node root = null;
        root = NewNode(4);
        root.left = NewNode(2);
        root.right = NewNode(9);
        root.left.left = NewNode(3);
        root.left.right = NewNode(8);
        root.right.right = NewNode(7);
        Console.WriteLine("The Tilt of whole tree is " + Tilt(root));
    }
}
// This code is contributed by guptapratik


Javascript




// JavaScript Program to find Tilt of Binary Tree
 
// A binary tree node has data, a left child, and a right child
class Node {
    constructor(data) {
        this.val = data;
        this.left = null;
        this.right = null;
    }
}
 
// Recursive function to calculate the sum of values in a subtree
function findSum(root) {
    if (root === null) {
        return 0;
    }
    return root.val + findSum(root.left) + findSum(root.right);
}
 
// Function to calculate the Tilt of the whole tree
function Tilt(root) {
    if (root === null) {
        return 0;
    }
 
    const left = Tilt(root.left);
    const right = Tilt(root.right);
 
    return Math.abs(findSum(root.left) - findSum(root.right)) + left + right;
}
 
// Helper function to create a new node with the given data
function newNode(data) {
    const temp = new Node(data);
    temp.left = null;
    temp.right = null;
    return temp;
}
 
// Driver code
(function () {
    // Let us construct a Binary Tree
    //     4
    //    / \
    //   2   9
    //  / \   \
    // 3   5   7
 
    let root = null;
    root = newNode(4);
    root.left = newNode(2);
    root.right = newNode(9);
    root.left.left = newNode(3);
    root.left.right = newNode(8);
    root.right.right = newNode(7);
    console.log("The Tilt of whole tree is " + Tilt(root));
})();
 
 
// This code is contributed by guptapratik


Output

The Tilt of whole tree is 15


Complexity Analysis:

Time complexity: O(n2), where n is the number of nodes in binary tree.
Auxiliary Space: O(n) as in worst case, depth of binary tree will be n.

Efficient Approach:

The idea is to recursively traverse tree. While traversing, we keep track of two things, sum of subtree rooted under current node, tilt of current node. Sum is needed to compute tilt of parent. 

Implementation:

C++




// CPP Program to find Tilt of Binary Tree
 
#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 val;
    struct Node *left, *right;
};
 
/* Recursive function to calculate Tilt of
  whole tree */
int traverse(Node* root, int* tilt)
{
    if (!root)
        return 0;
 
    // Compute tilts of left and right subtrees
    // and find sums of left and right subtrees
    int left = traverse(root->left, tilt);
    int right = traverse(root->right, tilt);
 
    // Add current tilt to overall
    *tilt += abs(left - right);
 
    // Returns sum of nodes under current tree
    return left + right + root->val;
}
 
/* Driver function to print Tilt of whole tree */
int Tilt(Node* root)
{
    int tilt = 0;
    traverse(root, &tilt);
    return tilt;
}
 
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->val = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Driver code
int main()
{
    /* Let us construct a Binary Tree
        4
       / \
      2   9
     / \   \
    3   5   7 */
 
    Node* root = NULL;
    root = newNode(4);
    root->left = newNode(2);
    root->right = newNode(9);
    root->left->left = newNode(3);
    root->left->right = newNode(8);
    root->right->right = newNode(7);
    cout << "The Tilt of whole tree is " << Tilt(root);
 
    return 0;
}


Java




// Java Program to find Tilt of Binary Tree
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 val;
    Node left, right;
}
// Class to hold the tree's tilt value
static class T{
    int tilt = 0;
}
   
/* Recursive function to calculate Tilt of
whole tree */ 
static int traverse(Node root, T t)
{
    if (root == null)
        return 0;
 
    // Compute tilts of left and right subtrees
    // and find sums of left and right subtrees
    int left = traverse(root.left, t);
    int right = traverse(root.right, t);
 
    // Add current tilt to overall
    t.tilt += Math.abs(left - right);
 
    // Returns sum of nodes under current tree
    return left + right + root.val;
}
 
/* Driver function to print Tilt of whole tree */
static int Tilt(Node root)
{
    T t = new T();
    traverse(root, t);
    return t.tilt;
}
 
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
static Node newNode(int data)
{
    Node temp = new Node();
    temp.val = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
 
// Driver code
public static void main(String[] args)
{
    /* Let us construct a Binary Tree
         4
        / \
       2   9
      / \   \
     3   5   7
    */
 
    Node root = null;
    root = newNode(4);
    root.left = newNode(2);
    root.right = newNode(9);
    root.left.left = newNode(3);
    root.left.right = newNode(8);
    root.right.right = newNode(7);
    System.out.println("The Tilt of whole tree is " + Tilt(root));
}
}


Python3




# Python3 Program to find Tilt of
# Binary Tree
 
# class that allocates a new node
# with the given data and
# None left and right pointers.
class newNode:
    def __init__(self, data):
        self.val = data
        self.left = self.right = None
 
# Recursive function to calculate
# Tilt of whole tree
def traverse(root, tilt):
    if (not root):
        return 0
 
    # Compute tilts of left and right subtrees
    # and find sums of left and right subtrees
    left = traverse(root.left, tilt)
    right = traverse(root.right, tilt)
 
    # Add current tilt to overall
    tilt[0] += abs(left - right)
 
    # Returns sum of nodes under
    # current tree
    return left + right + root.val
 
# Driver function to print Tilt
# of whole tree
def Tilt(root):
    tilt = [0]
    traverse(root, tilt)
    return tilt[0]
 
# Driver code
if __name__ == '__main__':
     
    # Let us construct a Binary Tree
    #     4
    #    / \
    #   2   9
    #  / \   \
    # 3   5   7
    root = None
    root = newNode(4)
    root.left = newNode(2)
    root.right = newNode(9)
    root.left.left = newNode(3)
    root.left.right = newNode(8)
    root.right.right = newNode(7)
    print("The Tilt of whole tree is",
                           Tilt(root))
 
# This code is contributed by PranchalK


C#




// C# Program to find Tilt of Binary Tree
using System;
 
class GfG
{
 
/* A binary tree node has data, pointer to
left child and a pointer to right child */
public class Node
{
    public int val;
    public Node left, right;
}
 
/* Recursive function to calculate Tilt of
whole tree */
public class T
{
    public int tilt = 0;
}
static int traverse(Node root, T t )
{
    if (root == null)
        return 0;
 
    // Compute tilts of left and right subtrees
    // and find sums of left and right subtrees
    int left = traverse(root.left, t);
    int right = traverse(root.right, t);
 
    // Add current tilt to overall
    t.tilt += Math.Abs(left - right);
 
    // Returns sum of nodes under current tree
    return left + right + root.val;
}
 
/* Driver function to print Tilt of whole tree */
static int Tilt(Node root)
{
    T t = new T();
    traverse(root, t);
    return t.tilt;
}
 
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
static Node newNode(int data)
{
    Node temp = new Node();
    temp.val = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
 
// Driver code
public static void Main(String[] args)
{
    /* Let us construct a Binary Tree
        4
       / \
      2   9
     / \   \
    3   5   7 */
 
    Node root = null;
    root = newNode(4);
    root.left = newNode(2);
    root.right = newNode(9);
    root.left.left = newNode(3);
    root.left.right = newNode(8);
    root.right.right = newNode(7);
    Console.WriteLine("The Tilt of whole tree is " + Tilt(root));
}
}
 
// This code contributed by Rajput-Ji


Javascript




<script>
 
    // JavaScript Program to find Tilt of Binary Tree
     
    /* A binary tree node has data, pointer to
    left child and a pointer to right child */
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.val = data;
        }
    }
 
    /* Recursive function to calculate Tilt of
    whole tree */
      let tilt = 0;
     
    function traverse(root)
    {
        if (root == null)
            return 0;
 
        // Compute tilts of left and right subtrees
        // and find sums of left and right subtrees
        let left = traverse(root.left, tilt);
        let right = traverse(root.right, tilt);
 
        // Add current tilt to overall
        tilt += Math.abs(left - right);
 
        // Returns sum of nodes under current tree
        return left + right + root.val;
    }
 
    /* Driver function to print Tilt of whole tree */
    function Tilt(root)
    {
        traverse(root);
        return tilt;
    }
 
    /* Helper function that allocates a
    new node with the given data and
    NULL left and right pointers. */
    function newNode(data)
    {
        let temp = new Node(data);
        return temp;
    }
     
    /* Let us construct a Binary Tree
        4
       / \
      2   9
     / \   \
    3   5   7
    */
   
    let root = null;
    root = newNode(4);
    root.left = newNode(2);
    root.right = newNode(9);
    root.left.left = newNode(3);
    root.left.right = newNode(8);
    root.right.right = newNode(7);
    document.write("The Tilt of whole tree is " + Tilt(root));
   
</script>


Output

The Tilt of whole tree is 15


Complexity Analysis: 

  • Time complexity: O(n), where n is the number of nodes in binary tree.
  • Auxiliary Space: O(n) as in worst case, depth of binary tree will be n.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads