All problems

Problem 265

Delete Node in a BST

Medium · 20 pts · Tree, Binary Search Tree

Problem

You are given a binary search tree with distinct values and a value K. Delete the node holding K, if there is one, and print the resulting tree in level order. If K is not in the tree, print the tree unchanged. Use these exact rules. A node with no children is removed. A node with one child is replaced by that child. A node with two children takes the value of its in-order successor, which is the smallest value in its right subtree, and that successor node is then deleted from the right subtree using the same rules.

Input

First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child. Third line: the value K.

Output

Print the tree in level order with 'null' for missing children and no trailing nulls, space-separated, or EMPTY if the tree becomes empty.

Constraints

1 <= number of nodes <= 10000; values are distinct

Example input

7
5 3 6 2 4 null 7
3

Example output

5 4 6 2 null null 7

Explanation

The node 3 has two children, 2 and 4. Its in-order successor is 4, the smallest value in its right subtree, so 3 becomes 4 and the old leaf 4 is removed. The tree becomes 5 with children 4 and 6, 4 keeps the child 2, and 6 keeps the child 7.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Path Sum II Next: Cousins in Binary Tree