Given a Binary tree and a key in the binary tree, find the node right to the given key. If there is no node on right side, then return NULL.
For example, consider the following Binary Tree. Output for 2 is 6, output for 4 is 5. Output for 10, 6 and 5 is NULL.
For example, consider the following Binary Tree. Output for 2 is 6, output for 4 is 5. Output for 10, 6 and 5 is NULL.
10
/ \
2 6
/ \ \
8 4 5
Solution: The idea is to do level order traversal of given Binary Tree. When we find the given key, we just check if the next node in level order traversal is of same level, if yes, we return the next node, otherwise return NULL.
// Java program to find next right of a given keyimportjava.util.LinkedList;importjava.util.Queue;// A binary tree nodeclassNode{intdata;Node left, right;Node(intitem){data = item;left = right =null;}}classBinaryTree{Node root;// Method to find next right of given key k, it returns NULL if k is// not present in tree or k is the rightmost node of its levelNode nextRight(Node first,intk){// Base Caseif(first ==null)returnnull;// Create an empty queue for level order tarversal// A queue to store node addressesQueue<Node> qn =newLinkedList<Node>();// Another queue to store node levelsQueue<Integer> ql =newLinkedList<Integer>();intlevel =0;// Initialize level as 0// Enqueue Root and its levelqn.add(first);ql.add(level);// A standard BFS loopwhile(qn.size() !=0){// dequeue an node from qn and its level from qlNode node = qn.peek();level = ql.peek();qn.remove();ql.remove();// If the dequeued node has the given key kif(node.data == k){// If there are no more items in queue or given node is// the rightmost node of its level, then return NULLif(ql.size() ==0|| ql.peek() != level)returnnull;// Otherwise return next node from queue of nodesreturnqn.peek();}// Standard BFS steps: enqueue children of this nodeif(node.left !=null){qn.add(node.left);ql.add(level +1);}if(node.right !=null){qn.add(node.right);ql.add(level +1);}}// We reach here if given key x doesn't exist in treereturnnull;}// A utility function to test above functionsvoidtest(Node node,intk){Node nr = nextRight(root, k);if(nr !=null)System.out.println("Next Right of "+ k +" is "+ nr.data);elseSystem.out.println("No next right node found for "+ k);}// Driver program to test above functionspublicstaticvoidmain(String args[]){BinaryTree tree =newBinaryTree();tree.root =newNode(10);tree.root.left =newNode(2);tree.root.right =newNode(6);tree.root.right.right =newNode(5);tree.root.left.left =newNode(8);tree.root.left.right =newNode(4);tree.test(tree.root,10);tree.test(tree.root,2);tree.test(tree.root,6);tree.test(tree.root,5);tree.test(tree.root,8);tree.test(tree.root,4);}}