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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- 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 left and right leaf nodes separately in Binary Tree
- Print leaf nodes in binary tree from left to right using one stack
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Find sum of all left leaves in a given Binary Tree
- Print Left View of a Binary Tree
- Convert left-right representation of a binary tree to down-right
- Left-Right traversal of all the levels of 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
- Sum of Nodes and respective Neighbors on the path from root to a vertex V
- Deepest left leaf node in a binary tree | iterative approach
- Sum of all nodes in a binary tree
- Product of all nodes in a Binary Tree
- Sink Odd nodes in 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