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.
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
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.
The Tilt of whole tree is 15
- 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.
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Minimum swap required to convert binary tree to binary search tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Binary Tree to Binary Search Tree Conversion
- Binary Tree to Binary Search Tree Conversion using STL set
- Check whether a binary tree is a full binary tree or not
- Check if a binary tree is subtree of another binary tree | Set 2
- Check whether a given binary tree is skewed binary tree or not?
- Check if a binary tree is subtree of another binary tree | Set 1
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Check if a given Binary Tree is height balanced like a Red-Black Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.