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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Sum of nodes in the left view of the given binary tree
- 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
- Print left and right leaf nodes separately in Binary Tree
- 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 )
- Print Left View of a Binary Tree
- Get maximum left node in binary tree
- Convert left-right representation of a binary tree to down-right
- Find sum of all left leaves in a given Binary Tree
- Left-Right traversal of all the levels of Binary tree
- Construct XOR tree by Given leaf nodes of Perfect 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
- Sum of all nodes in a binary tree
- Connect nodes at same level
- Sink Odd nodes in Binary Tree
- Product of all nodes in 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.
Improved By : andrew1234