...

/

Level Order Successor (easy)

Level Order Successor (easy)

Problem Statement

Given a binary tree and a node, find the level order successor of the given node in the tree. The level order successor is the node that appears right after the given node in the level order traversal.

Example 1:

Example 2:

Example 3:

Try it yourself

Try solving this question here:

import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
};
class LevelOrderSuccessor {
public static TreeNode findSuccessor(TreeNode root, int key) {
// TODO: Write your code here
return null;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
TreeNode result = LevelOrderSuccessor.findSuccessor(root, 3);
if (result != null)
System.out.println(result.val + " ");
root = new TreeNode(12);
root.left = new TreeNode(7);
root.right = new TreeNode(1);
root.left.left = new TreeNode(9);
root.right.left = new TreeNode(10);
root.right.right = new TreeNode(5);
result = LevelOrderSuccessor.findSuccessor(root, 9);
if (result != null)
System.out.println(result.val + " ");
result = LevelOrderSuccessor.findSuccessor(root, 12);
if (result != null)
System.out.println(result.val + " ");
}
}

Solution

This problem follows the Binary Tree Level Order Traversal pattern. We can follow the same BFS approach. The only difference will be that we will not keep track of all the levels. ...