The problem is how you handle the case when your tree reaches the bottom.
In you case if you use if
statement it should keep oupting 7 while you do preOrder(7) because
When you do the recursion
return preordernextRecursive(node.parent);
Node will become 5 and fall in the below statement since node.left = 7
else if (node.left != null) {
return node.left.element;
}
Solution 1 (Using recursion)
Instead of using if else
you can try using while loop:
while (node.parent != null) {
if (node.parent.left == node && node.parent.right != null) {
return node.parent.right.element;
}
node = node.parent;
}
This simply keep moving up until it reached the root element and return the node of right subtree,
Solution 2 (Just while loop)
Node<E> current = node;
while (current.parent != null) {
if (current.parent.left == current && current.parent.right != null) {
return current.parent.right.element;
}
current = current.parent;
}
This is similar to solution 1 but remove the recursion part, which should have a slightly better space complexity.
probably not the best solutions but should be able to solve your problem !
This is my first time to comment here (and literally just made an account)
Hope this is clear for you !🙂