Skip to content

Conversation

@ErdemT09
Copy link
Collaborator

@ErdemT09 ErdemT09 commented May 8, 2021

Issue.
We have previously encountered in this question, so it might be helpful to revise that before solving this.
is: inorder successor

The idea is simple:
If a node has a right node, then the is should be the leftmost node at that side of tree.
Else, if a node has a parent node and its left node is the node, then the is is the node's parent.
Else, if a node has a parent node and its right node is the node, then the is is the parent's parent if its parent is its corresponding left node, if its however the right node, then we must recursively climb up the tree, until we find a node that is its parent's left node.
If all these do not work, then the result is null, as there is no is.

@ErdemT09 ErdemT09 changed the title 510-Initial solution 510. Inorder Successor in BST II May 8, 2021
}
return null;
}
return findSuc(start);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we alter with this:
return findSuc(start.right);

Comment on lines 10 to 16
while (start.parent != null) {
if (start.parent.left == start) {
return start.parent;
}
start = start.parent;
}
return null;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can combine if and while like this:

  public Node inorderSuccessor(Node start) {
        if (start == null) {
            return null;
        }
      if (start.right != null) return findSuc(start.right);
       
      while (start.parent != null && start.parent.left != start) {
                
                start = start.parent;
       }
      
       return start.parent;
     
        
    }

image

@ErdemT09
Copy link
Collaborator Author

ErdemT09 commented May 8, 2021

Would an iterative solution be faster? Such as this. Again, theoretically, it shouldn't be.

@altay9
Copy link
Collaborator

altay9 commented May 8, 2021

Would an iterative solution be faster? Such as this. Again, theoretically, it shouldn't be.

The iterative one is slower.
I think recursive is a perfect match for Tree questions in general.
image

@ErdemT09 ErdemT09 merged commit 581f766 into master May 8, 2021
@ErdemT09 ErdemT09 deleted the 510.-Inorder-Successor-in-BST-II branch May 8, 2021 15:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants