Approach
Breadth-first search
For Minimum Number of Operations to Sort a Binary Tree by Level, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 38 lines of Java from the credited upstream file 2471.java.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int minimumOperations(TreeNode root) {3 int ans = 0;4 Queue<TreeNode> q = new LinkedList<>(Arrays.asList(root));5 6 7 8 9 10 while (!q.isEmpty()) {11 List<Integer> vals = new ArrayList<>();12 List<Integer> ids = new ArrayList<>();13 for (int sz = q.size(); sz > 0; --sz) {14 TreeNode node = q.poll();15 vals.add(node.val);16 if (node.left != null)17 q.offer(node.left);18 if (node.right != null)19 q.offer(node.right);20 }21 for (int i = 0; i < vals.size(); ++i)22 ids.add(i);23 Collections.sort(ids, (i, j) -> vals.get(i) - vals.get(j));24 for (int i = 0; i < ids.size(); ++i)25 for (; ids.get(i) != i; ++ans)26 swap(ids, i, ids.get(i));27 }28 29 return ans;30 }31 32 private void swap(List<Integer> ids, int i, int j) {33 final int temp = ids.get(i);34 ids.set(i, ids.get(j));35 ids.set(j, temp);36 }37}38