Vertical zig-zag traversal of a tree in JavaThe goal is to get the outcome of the items in the Vertical Zig-Zag traversal order given a Binary Tree. A tree's vertical zigzag traversal is described as follows:
Example 1: Input: Output: The order of elements after traversing is: 21, 27, 23, 28, 22, 24, 26, 25 Explanation:
AlgorithmStep 1: Make a vector tree[] in which all of the tree's nodes at level i will be stored in tree[i]. Step 2: Take two pointers, p1 and p2, respectively, pointing to the first and last levels. Step 3: Now, use these two pointers to begin printing the nodes alternately (from left to right for p2 and from right to left for p1). Step 4: Proceed to the next level if there are no more nodes in the level that p1 points to, and back to the previous level if there are no more nodes in the level that p2 points to. Implementation:FileName: VerticalZigZag.java Output: The order after traversing: 21 27 23 28 22 24 26 25 Complexity Analysis: The time complexity is O(n) and the space complexity is O(n). |