Binary Tree Inversions
Given a binary tree, write a function that returns the number of inversions in the tree. An inversion is defined as a pair of nodes where the ancestor node has a greater value than its descendant node.
[ [ 10, 5, 15, 2, 7, null, 18 ] ]
Explanation. There are three inversions: 10 > 5, 10 > 2, 10 > 7.
[ [ 3, 2, 5, 1, null, 4, 6 ] ]
Explanation. There are two inversions: 3 > 1 and 3 > 2.
[ [ 1, 2, 3, 4, 5, 6, 7 ] ]
Explanation. There are no inversions as the tree is a perfect increasing sequence.
[ [ 7, 7, 7, 7, 7 ] ]
Explanation. All elements being equal, there are no inversions.
Follow-up: Can you optimize your solution to run in better than O(n^2) time complexity, where n is the number of nodes?
The tree will have at least one node and at most 1000 nodes. Each node's value will be an integer between 1 and 10,000.
- Views
- 3