Given a binary tree with the node structure containing a data part, left and right pointers and an arbitrary pointer(abtr). The node’s value can be any positive integer. The problem is to create odd and even loops in a binary tree. An odd loop is a loop which connects all the nodes having odd numbers and similarly even loop is for nodes having even numbers. To create such loops, the abtr pointer of each node is used. An abtr pointer of an odd node(node having odd number) points to some other odd node in the tree. A loop must be created in such way that from any node we could traverse all the nodes in the loop to which the node belongs.
Consider the binary tree given below 1 / \ 2 3 / \ / \ 4 5 6 7 Now with the help of abtr pointers of node, we connect odd and even nodes as: Odd loop 1 -> 5 -> 3 -> 7 -> 1(again pointing to first node in the loop) Even loop 2 -> 4 -> 6 -> 2(again pointing to first node in the loop) Nodes in the respective loop can be arranged in any order. But from any node in the loop we should be able to traverse all the nodes in the loop.
Approach: The following steps are:
- Add pointers of the nodes having even and odd numbers to even_ptrs and odd_ptrs arrays respectively. Through any tree traversal we could get the respective node pointers.
- For both the even_ptrs and odd_ptrs array, perform:
- As the array contains node pointers, consider an element at ith index, let it be node, and the assign node->abtr = element at (i+1)th index.
- For last element of the array, node->abtr = element at index 0.
Odd nodes: 3 7 1 5 Even nodes: 2 4 6
Time Complexity: Equal to the time complexity of any recursive tree traversal which is O(n)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Tree Traversals (Inorder, Preorder and Postorder)
- Find the node with minimum value in a Binary Search Tree
- Write a program to Calculate Size of a tree | Recursion
- Write a Program to Find the Maximum Depth or Height of a Tree
- Write a program to Delete a Tree
- If you are given two traversal sequences, can you construct the binary tree?
- Convert a Binary Tree into its Mirror Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Lowest Common Ancestor in a Binary Search Tree.
- The Great Tree-List Recursion Problem.
- Check sum of Covered and Uncovered nodes of Binary Tree
- Level Order Tree Traversal
- Program to count leaf nodes in a binary tree
- A program to check if a binary tree is BST or not
- Check for Children Sum Property in a Binary Tree