After doing some exercises to hone my binary tree skills, I decided to implement the splay tree as described in Wikipedia: Splay tree .
One thing that I am not getting is part of the insert.
It says:
First we look for x in the splay tree. If x does not already exist, we will not find it, but the parent node y. Secondly, we perform the splay operation on y, which moves y to the root of the splay tree. Third, we insert the new node x as root accordingly. So either y is the left or right child of the new root x.
My question is this: the text above seems too short compared to other examples in the article, why? There seems to be some flaws here. For example, after expanding the y node to the root, I cannot just blindly replace the root with x and bind y to x as a left or right child.
Suppose the value does not exist in the tree.
I have this tree:
10 / \ 5 15 / \ \ 1 6 20
and I want to insert 8. In the above description, I will find a 6-node, and in a regular binary tree, 8 will be added as the right child of the 6-node, however here I need to first translate the 6-node to the root:
6 / \ 5 10 / \ 1 15 \ 20
then one of these two is clearly erroneous:
8 8 \ / 6 6 / \ / \ 5 10 5 10 / \ / \ 1 15 1 15 \ \ 20 20 6 is not greater than 8 10 is not less than 8
It seems to me that the only way to do splaying first, and then correctly add the new value as root, will mean that I have to check the following criteria (to add a splayed node as the left child of the new root):
- node I lost to the root less than the new root (6 <8)
- the right-most child node I used in the root is also smaller than the new root (20 8)
However, if I split the node, I lost by taking the correct child and adding it as the right child of the new node, I would get the following:
8 / \ 6 10 / \ 5 15 / \ 1 20
But will this simple change always give me the right tree? It’s not easy for me to come up with an example, but can this lead to the following:
- The new value that I want to add is higher than the temporary root (node I went to the root directory), but also higher than the left-most child of the right child of the temporary root?
Those. a tree that would basically look like this after a reversal, but before I replaced the root?
10 / \ 5 15 / \ 11 20
and I want to add 13, which will make the new tree as follows:
13 / \ 10 15 / / \ 5 11 20 <-- 11, on the wrong side of 13
or will it never happen?
My second question: isn’t it easier to just rewrite the operation as follows:
First we look for x in the splay tree. If x does not already exist, we will not find it, but the parent node y. Then we add the new node as the left or right child of the parent node. . Thirdly, we perform a playback operation in the node we added which will move the new value to the root of the splay tree.
emphasize mine to show that I have changed.