#P3365. Minimum Modifications to Convert a Binary Tree into a Binary Search Tree

    ID: 16622 Type: Default 1000ms 256MiB

Minimum Modifications to Convert a Binary Tree into a Binary Search Tree

Minimum Modifications to Convert a Binary Tree into a Binary Search Tree

In computer science, a binary tree is an ordered tree in which each node has at most two children, referred to as the left child and the right child. Binary trees are widely used in various applications such as binary search trees and binary heaps.

A binary search tree (BST) is a binary tree that satisfies the following property: For every node p with key \(key[p]\), if the left child exists, then \(key[lch] < key[p]\); if the right child exists, then \(key[p] < key[rch]\). Moreover, this property must hold for every node in the tree, ensuring that all keys in the left subtree of any node are smaller than key[p] and all keys in the right subtree are larger than key[p].

Given an arbitrary binary tree with n nodes, you are allowed to modify the value of any node at most once. Each modification changes the node’s value to any integer (which can be negative, zero, or positive). Your task is to determine the minimum number of modifications required to convert the given binary tree into a binary search tree.

Note: The in-order traversal of a BST yields a strictly increasing sequence. Thus, one viable strategy is to compute the in-order traversal of the tree and then determine the longest strictly increasing subsequence (LIS). The minimum number of modifications needed is equal to the total number of nodes minus the length of the LIS.

If you manage to solve this problem, you might even get a share of the final assets!

inputFormat

The input begins with a single integer n (1 ≤ n ≤ 105), representing the number of nodes in the binary tree. The nodes are numbered from 1 to n, and node 1 is the root of the tree.

Then follow n lines. The i-th line contains three space-separated integers:

  • value: The integer value at node i.
  • l: The index of the left child of node i, or -1 if there is no left child.
  • r: The index of the right child of node i, or -1 if there is no right child.

outputFormat

Output a single integer representing the minimum number of nodes that need to be modified to transform the given binary tree into a binary search tree.

Explanation: If the in-order traversal of the tree yields a strictly increasing sequence, no modification is needed. Otherwise, find the length of the longest strictly increasing subsequence (LIS) of the in-order sequence and output n - (length of LIS).

sample

3
2 2 3
1 -1 -1
3 -1 -1
0