79526796

Date: 2025-03-22 00:49:52
Score: 0.5
Natty:
Report link

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 !🙂

Reasons:
  • Blacklisted phrase (1): to comment
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Karso