Inorder Successor in a Binary Tree

Given a node in an arbitrary binary tree, find its inorder successor. The successor is defined as the node that appears immediately after the given node in the in-order traversal of the tree. If the given node is the last node in this traversal, the successor should be NULL.

Input:

The input will have the following format:

The first line contains an integer 'T', the number of test cases.
Each test case consists of:
- A single line with integers representing the binary tree in level order (use -1 for NULL nodes).
- A single integer representing the value of the node for which the inorder successor is to be found.

Output:

For each test case, output a single line that contains the value of the inorder successor node, or 'NULL' if no inorder successor exists.

Example:

Consider the example of a binary tree given by levels:

altImage
Input:
4 -1 5 6
5
Output:
6

This shows that the inorder successor of node 5 in the given tree is 6.

Constraints:

  • 1 <= T <= 100
  • 2 <= N <= 103
  • 1 <= NODEVALUE <= 109
  • Time Limit: 1 sec.

Note:

Each node has a unique integer value. The node for which the successor is to be found is guaranteed to be part of the tree. Implementation is required only for finding the successor, as input/output handling is already managed.
Be the first one to answer
Add answer anonymously...
SAP Developer Associate Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter