Skip to content

How do you print a binary tree in vertical order? #1676

Answered by Emojees
Kuefo asked this question in Q&A
Discussion options

You must be logged in to vote

[Naive Approach] By Counting Nodes – O(n) time and O(1) space:
The idea is to traversing the entire linked list once to count the total number of nodes. After determining the total count, traverse the list again and stop at the (count/2)th node to return its value. This method requires two passes through the linked list to find the middle element.

[Expected Approach] By Tortoise and Hare Algorithm – O(n) time and O(1) space:
We can use the Hare and Tortoise Algorithm to find the middle of the linked list. Traverse linked list using a slow pointer (slow_ptr) and a fast pointer (fast_ptr ). Move the slow pointer to the next node(one node forward) and the fast pointer to the next of the next…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by Kuefo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants