VOOZH about

URL: https://www.geeksforgeeks.org/dsa/inorder-succesor-node-binary-tree/

⇱ Inorder successor in Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Inorder successor in Binary Tree

Last Updated : 30 Oct, 2024

Given a binary tree and a node, the task is to find the inorder successor of this node. Inorder Successor of a node in the binary tree is the next node in the Inorder traversal of the Binary Tree. Inorder Successor is NULL for the last node in Inorder traversal.

In the below diagram, inorder successor of node 4 is 2, 1 is 3 and 5 is 1.

👁 Image

Using Reverse Inorder - O(n) Time and O(h) Space

We do a reverse inorder traversal and keep track of the last visited node.

If we find the node and successor in the right subtree, we return it.

  • If root's data is same as target, return the last visited node in the right subtree.
  • Update last visited node and recur for the left subtree.

Below is the implementation of above approach: 


Output
2

Using Morris Traversal - O(n) Time and O(1) Space

We can optimize the auxiliary space used using Morris Traversal (A standard technique to do inorder traversal without stack and recursion)

Below is the implementation of the above approach: 


Output
2

Using BST tree properties - O(h) Time and O(1) Space

We begin traversal from root. For every node, we need to take care of 3 cases for to find its inorder successor.

  • Right child of node is not NULL : . The successor will be the leftmost node in its right subtree. For example, successor for 1 is 3
  • The node is the Rightmost in Tree : The successor is NULL. For example, node 6 in the above diagram.
  • If right child of the node is NULL :. The successor must be an ancestor. Travel up using the parent pointer until we see a node which is left child of its parent. The parent of such a node is the successor.

Please refer to Inorder Successor in Binary Search Tree for implementation.

Comment
Article Tags: