1. 程式人生 > >二叉搜尋樹刪除節點

二叉搜尋樹刪除節點

PTA-7-2 Delete Nodes in a Binary Search Tree (25 分)

Given a binary search tree with no same keys, you should output the level-order traversal sequence of this tree after some nodes are deleted.

When trying to remove a node from the tree, we follow the rules listed below:

  • If the node to be deleted is a leaf node, remove it directly;
  • If the node has left subtree, set its key to be the maximum key in its left subtree and remove the node in its left subtree with maximum key;
  • If the node doesn’t have left subtree but has right subtree, set its key to be the minimum key in its right subtree and remove the node in its right subtree with minimum key.

Input Specification:

Each input file contains one test case. The first line of each test contains a number N (1<N<100, the count of nodes in the binary search tree). The second line gives the pre-order traversal sequences of the binary search tree, consisting of N different numbers separated by a space. The third line gives a number K (0<K<N, the count of nodes to be deleted). And the next line gives K numbers, representing keys of nodes to be deleted. It is guaranteed that no delete operation will fail.

Output Specification:

Output the level-order traversal sequence of the tree. Numbers in the sequences must be separated by a space, and no extra space is allowed at the end of line.

Sample Input:

7
4 2 1 3 6 5 7
2
3 6

Sample Output:

4 2 5 1 7

參考資料:二叉搜尋樹簡單介紹           二叉搜尋樹後序遍歷      二叉搜尋樹的插入