怎么用python实现这个问题?

Problem 5.3. Fix the Tree! (Hard)
Input file name: fix.in
Output file name: fix.out
Time limit: 10 s
Memory limit: 256 MB

A binary search tree (BST) is an arborescence (i. e. a directed rooted tree with all arcs directed from the root towards leaves),
whose vertices each store a key and each have at most two distinguished children (adjacent to head ends of arcs),
commonly called left and right and being the roots of the left and the right subtrees correspondingly.
The tree additionally satisfies the binary search tree property, which states that the key of each vertex must be greater than all keys stored in the left subtree,
and less than all keys in the right subtree.
You develop a database engine and maintain a BST over integer keys in order to perform fast lookups.
The tree is stored in a data file. One day the file got damaged due to a hardware failure.
You did your best and completely recovered the tree vertices and arcs, but some keys are corrupt (you don't know exactly).
The tree is rooted and binary as before, but may have lost its search properties…
One obvious way to make the BST valid is to select some vertices and change their keys without rebuilding the tree structure.
Note that all the keys should be positive integers. Duplicate keys are not permitted.
Compute the minimum number of keys that can be changed to make the BST valid.

img

Input
Input contains several test cases. For each test case, the first line contains the number NNN of the vertices in the tree (1≤N≤300000).
The iiith of the following NNN lines describes the iiith vertex: a key (an integer between 111 and 10910^9109, inclusive) and an index of the parent vertex (which is 000 for root vertex or a number between 111 and i−1i-1i−1,
inclusive, for any other vertex, followed by a letter which specifies whether the vertex is the left (L) or the right (R) child of its parent).
The last line of input contains an integer 000, and this case should not be processed. The sum of NNN over all test cases in a single file does not exceed 300000
Output
For each test case, write a single line containing the minimum number of changes that must be applied to the tree to make it valid.

img

这个就是二叉树的删除节点和增添和删除,网上有有详细教程的,不设置算法限制的话你可以把写好的二叉树先遍历,然后存入一棵二叉搜索树里面,建议用层次遍历

可以用python pandas 数据框 编写 BST算法

涉及二叉树的搜索以及优化问题,站内搜索即可