Connect Same Level Siblings of a Binary Tree
Given a binary tree, at each level in the hierarchy, connect each node to the one on its right.
We'll cover the following...
Statement
Given a binary tree, connect all nodes at the same hierarchical level. We need to connect them from left to right, such that the next pointer of each node points to the node on its immediate right. The next pointer of the right-most node at each level will be NULL.
For this problem, each node in the binary tree has one additional pointer (the next
pointer), along with the left
and right
pointers.
Example
Let’s consider the following binary tree as an example:
After connecting the nodes at each level, the tree will look like this:
Sample input
The input list below represents the level-order traversal of the binary tree shown above, while the value that follows represents the node whose next node we need to find:
[100, 50, 200, 25, 75, 125, 300, 10, 350, 15], 75
Expected output
Only if the next pointer of the node with value 75 is correctly set up will the correct result, 125, be returned.
125
Try it yourself
Note: The binary tree node’s class has members
left
andright
to store references to other nodes, along with the memberdata
to hold the node’s value.
#include <iostream>#include <vector>#include "BinaryTree.cpp"using namespace std;typedef BinaryTreeNode* NodePtr;void PopulateNextPointers(NodePtr node) {// TODO: Write - Your - Code}// Do not modify the code below// Function to find the given node and return its next nodeBinaryTreeNode* GetNextNode(BinaryTreeNode* node, int node_data) {// Performing Binary Searchwhile (node != nullptr && node_data != node->data) {if (node_data < node->data) {node = node->left;} else {node = node->right;}}// If node is not found return -1 else return its next nodeif (node == nullptr) {BinaryTreeNode* non_existing_node = new BinaryTreeNode(-1);return non_existing_node;} else {return node->next;}}
Solution
We need to connect all nodes at each hierarchical level ...