Problem
Find Inorder Successor in Binary Tree. OR Given a Binary tree, find the inorder successor of a node.
Definition
See the definition here.
Examples
Example 1:
|
|
|
|
Similar Problems
Inorder Successor in Binary Search Tree Using Parent link Inorder Successor in Binary Search Tree
Solution
Method 1 - Inorder Traversal
To find the in-order successor of a node in a general binary tree (not necessarily a binary search tree), we need to perform an in-order traversal and keep track of the last visited node. The in-order successor of a node is the node that comes immediately after it in an in-order traversal of the tree.
Here are the steps we can follow:
- In-order Traversal: Perform an in-order traversal of the binary tree.
- Track Last Visited Node: Keep track of the last visited node.
- Identify Successor: When the current node matches the target node, the next node visited will be its in-order successor.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the number of nodes in the tree. This is because we perform an in-order traversal of the entire tree. - 🧺 Space complexity:
O(h)
, whereh
is the height of the tree. This is due to the recursive call stack used in the in-order traversal. In the worst case, the space complexity can be O(n) for a skewed tree.