To implement a recursive solution for the Zig Zag Level
Order Traversal in Java, we can use a depth-first approach where we keep track
of the current level and incorporate nodes into the outcome following a zigzag arrangement. This
approach involves maintaining a list of lists, where each list corresponds to a
level in the binary tree. We alternate the order of insertion for each level.
Zig Zag Level Order Traversal (Iteration) Implementation
|
import
java.util.*; class
Node<T> { T data; Node<T> left, right; Node(T item) { data = item; left = null; } } public class ProcessZigZagTraversal { public static <T>
List<List<T>> processZigzagLevelOrder(Node<T> root) { List<List<T>> result =
new ArrayList<>(); if (root == null) { return result; } Deque<Node<T>>
currentLevel = new ArrayDeque<>(); currentLevel.offer(root); boolean leftToRight = true; while (!currentLevel.isEmpty()) { int size = currentLevel.size(); List<T> currentLevelResult
= new ArrayList<>(size); Deque<Node<T>>
nextLevel = new ArrayDeque<>(); for (int i = 0; i < size; i++)
{ Node<T> currentPresentNode; if (leftToRight) { currentPresentNode =
currentLevel.pollFirst();
currentLevelResult.add(currentPresentNode.data); if (currentPresentNode.left !=
null) {
nextLevel.offerLast(currentPresentNode.left); } if (currentPresentNode.right !=
null) {
nextLevel.offerLast(currentPresentNode.right); } } else { currentPresentNode =
currentLevel.pollLast();
currentLevelResult.add(currentPresentNode.data); if (currentPresentNode.right !=
null) {
nextLevel.offerFirst(currentPresentNode.right); } if (currentPresentNode.left !=
null) {
nextLevel.offerFirst(currentPresentNode.left); } } } result.add(currentLevelResult); currentLevel = nextLevel; leftToRight = !leftToRight; //
Toggle direction } return result; } public static void main(String[] args) { Node<Integer> root = new
Node<>(1); root.left = new Node<>(21); root.right = new Node<>(31); root.left.left = new Node<>(41); root.left.right = new
Node<>(51); root.right.left = new
Node<>(61); root.right.right = new
Node<>(71); List<List<Integer>>
result = processZigzagLevelOrder(root); System.out.println("Zigzag Level
Order Traversal:"); for (List<Integer> level :
result) { System.out.println(level); } } } |
Explanation
- Node
Class: A simple Node class to represent nodes in the binary tree,
where each node contains data and references to left and right child
nodes.
- zigzagLevelOrder
Method:
- The
method returns a list of lists where each sublist contains the nodes at a
particular level, traversed in the zigzag pattern.
- A Deque
(double-ended queue) is used to allow efficient removal from both ends
depending on the current direction of traversal.
- The
method toggles the direction (left to right or right to left) after
processing each level.
- Traversal
Logic:
- If
traversing from left to right:
- Nodes
are removed from the front of the queue.
- Children
are added to the end of the queue.
- If
traversing from right to left:
- Nodes
are removed from the back of the queue.
- Children
are added to the front of the queue.
Zig Zag Level Order Traversal (Recursive) Implementation
Here’s how you can implement the Zig Zag Level Order
Traversal recursively:
java
|
import
java.util.*; class
Node<T> { T data; Node<T> left, right; Node(T item) { data = item; left = right = null; } } public class
ZigZagTraversalRecursive { public static <T>
List<List<T>> zigzagLevelOrder(Node<T> root) { List<List<T>> result =
new ArrayList<>(); zigzagLevelOrderHelper(root, result,
0); return result; } private static <T> void processZigzagLevelOrderHelper(Node<T> node, List<List<T>> result,
int level) { if (node == null) { return; } // Ensure the result list has a
sublist for the current level if (level >= result.size()) { result.add(new
LinkedList<>()); // Using LinkedList to efficiently add at the
beginning } // Add the current node's value to
the list at this level if (level % 2 == 0) { // Even level, add to the end
(left-to-right) result.get(level).add(node.data); } else { // Odd level, add to the
beginning (right-to-left) result.get(level).add(0,
node.data); } // Recur for left and right children processZigzagLevelOrderHelper(node.left,
result, level + 1); processZigzagLevelOrderHelper(node.right,
result, level + 1); } public static void main(String[] args) { Node<Integer> root = new
Node<>(11); root.left = new Node<>(12); root.right = new Node<>(13); root.left.left = new Node<>(14); root.left.right = new
Node<>(15); root.right.left = new
Node<>(16); root.right.right = new
Node<>(17); List<List<Integer>>
result = zigzagLevelOrder(root); System.out.println("Zigzag Level
Order Traversal (Recursive):"); for (List<Integer> level :
result) { System.out.println(level); } } } |
Explanation
- Node Class: The Node class represents each node in the binary tree, holding the data and pointers to the left and right children.
- zigzagLevelOrder Method:
- This is the main method that initializes the result list and calls the helper method zigzagLevelOrderHelper to perform the traversal.
- zigzagLevelOrderHelper Method:
- Base
Case: If the current node is null, the recursion stops.
- Current
Level Handling:
- If
the level is even, it adds the node's data to the end of the list
corresponding to that level.
- If
the level is odd, it adds the node's data to the beginning of the list
for that level (to achieve the right-to-left order).
- Recursive
Calls: The method recursively processes the left and right subtrees,
increasing the level by 1 for each recursive call.
Example Output
For the tree:
text
|
11 / \ 12 13 / \ / \ 14 15 16 17 |
The Zig Zag Level Order Traversal output will be:
text
|
Zigzag Level
Order Traversal (Recursive): [11] [13,12] [14, 15, 16, 17] |
Summary
This recursive solution efficiently handles the Zig Zag
Level Order Traversal by leveraging the recursive depth-first search (DFS)
approach. It alternates between adding elements to the front and the back of
each level's list based on whether the level is odd or even, respectively. This guarantees that the zigzag configuration is preserved during the entire traversal.
| Binary Level Order Traversal in Zig Zag pattern |
For More Java Related information, visit Ø
Streams
Lambdas Collectors and Functional Interfaces in Java 8 Ø
Java
8 support static method or default method or both in the interface Ø
Serialization
understanding Ø
Garbage
Collection Under Standing Ø
How
work Garbage Collection in Java Ø
Under
Standing Of Mutable and Immutable Class For More sort information, visit: Ø
Selection
Sort with iteration wise per step Ø
Bubble
Sort with each iteration how it is work Ø
Merge
sort of Each step how it is working Ø
Quick
Sort per iteration what happen Ø
Sorting
Of a list multiple attribute wise two technique Ø
Seat
Arrangement in Sorting Order Like 1A-1E, 3C-3G etc Ø
How
to sort 10 billion numbers Ø
Merge
Sort simple under standing Ø
For Math information, visit: Ø
Calculating
the area of a triangle Ø
The
method for calculating the area of a rectangle in Java Ø
The value of π =
3.14159 in java [Click
Here] |
0 Comments