Given a Binary Tree, where each node contains an extra empty pointer initially null. The task is to connect all nodes of the binary tree to their left neighbour at the same level using this extra pointer.
Input : A / \ B C / \ \ D E F Output : NULL<--A / \ NULL<--B<--C / \ \ NULL<--D<--E<--F
We can use Pre-order traversal of tree passing the level of the node at each call. The root node is at level 0. While traversing we store the recently seen node at that level in an array of node pointers. The pre-order traversal ensures that the node in the array at a particular level is left neighbour of upcoming node at the same level.
Below is the implementation of the above approach:
Following are populated leftNeighbour pointers in the tree: leftNeighbour of 10 is -1 leftNeighbour of 8 is -1 leftNeighbour of 2 is 8 leftNeighbour of 3 is -1
- Print all leaf nodes of a binary tree from right to left
- Print all leaf nodes of a Binary Tree from left to right
- Print leaf nodes in binary tree from left to right using one stack
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Find sum of all left leaves in a given Binary Tree
- Convert left-right representation of a binary tree to down-right
- Print Left View of a Binary Tree
- Get maximum left node in binary tree
- Deepest left leaf node in a binary tree
- Iterative Method To Print Left View of a Binary Tree
- Deepest left leaf node in a binary tree | iterative approach
- Connect nodes at same level
- Sum of all nodes in a binary tree
- Sum of all the Boundary Nodes of a Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.