The second step, can be implemented as a recursive function starting from the root and keeping track of your depth. Level Order Tree Traversal – Recursive Algorithm However, I have done my research about this question and I saw no mention of any recursive solution anywhere, so I decided to take a stab at it on my own. Now as soon as I read Binary Tree, I immediately thought: Recursion. It would seem somewhat simple to apply the zig zag tree traversal at the end of this. To further simplify the question, I decided to first solve the problem of “How to Print an Tree in Level Order Tree Traversal”, meaning we removed the zig zag portion. There might be multiple edge cases, but let us worry about those later. Of course this is just a basic binary tree and it’s a good point of start to build our algorithm. This would produce the output: A, B, C, G, F, E, D. With these clarification we can visualize a stub tree that would look like this: A zig zag tree traversal could go both ways, but for simplicity we will assume we want the right zig zag tree traversal. Do we go left-first or right-first? This is actually a great question.What is a zig zag tree traversal? Well as the name implies, is a traversal of the tree going zig zag each level, from top to bottom.Let us assume for this question that we are talking about a binary tree. Are we talking about any tree or a binary tree.I will try to explain step by step how to come up with a solution, so you get in the habit of applying this thought process to other problems as well.įirst as usual, let us try to clarify any assumptions: Now I found a few solutions to this problem over the internet, but none was really explaining how to get to the solution, instead just provide one. I got asked this question once in an interview. Write a method to find the zig zag tree traversal in a tree.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |