Minimum Number of Operations to Sort a Binary Tree by Level

You are given the root of a binary tree with unique values.

In one operation, you can choose any two nodes at the same level and swap their values.

Return the minimum number of operations needed to make the values at each level sorted in a strictly increasing order.

The level of a node is the number of edges along the path between it and the root node.

Example 1
              1
             / \
            /   \
           4     3
          / \   / \
         7   6 8   5
              /   /
             9   10
Inputroot = [1,4,3,7,6,8,5,null,null,null,null,9,null,10]
Output3
Swapping 4 and 3, then 7 and 5, then 8 and 7 makes every level strictly increasing using the minimum 3 operations.
Example 2
        1
       / \
      3   2
     / \ / \
    7  6 5  4
Inputroot = [1,3,2,7,6,5,4]
Output3
Swapping 3 and 2, then 7 and 4, then 6 and 5 makes every level strictly increasing using the minimum 3 operations.

Constraints

  • The number of nodes in the tree is in the range [1, 10^5].
  • 1 <= Node.val <= 10^5
  • All the values of the tree are unique.

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate