Binary Tree Level Order Traversal II

Binary Tree Level Order Traversal II. Given a binary tree, return the bottom-up level order traversal of its node’s values.  (ie, from left to right, level by level from leaf to root).

OR

Given a binary tree, return the reverse level order traversal of its nodes’ values. (i.e, from left to right and from the last level to starting level).

For Example –

In this example, we have printed the reverse level order traversal of a binary tree.

Binary Tree Level Order Traversal II

As you can see in this image, we have first printed the last level from left to right then we move up, and so on. We have already discussed the level order traversal in my previous tutorial. So, let’s think about how we can print the reverse level order traversal of a binary tree.

In this tutorial, I am going to discuss three approaches to solve this problem. Also, I have added a video tutorial link at the end of this post.

Binary Tree Reverse Level Order Traversal using Stacks and Queues – Java Code

In this example, I am going to discuss how we can do the reverse level traversal using Queue and Stack data structure.

The idea here is to do the level order traversal of a binary tree and put the values in a stack. Once traversal is complete, traverse the stack and put the values in a final result list.

The time complexity of this approach is O(n) and its space complexity is also O(n).

Binary Tree Level Order Traversal II – Java Code

Traverse the binary tree level by level. Once the traversal is complete reverse the result list. In this way, we get the reverse level order traversal of a binary tree.

Programming questions on binary tree

Check if two binary trees are identical

Binary Tree Reverse Level Order Traversal LeetCode Solution

The other way to solve this problem is to do the level order traversal and put each level result at the 0th index.

Programming Video Tutorials

Binary Tree Reverse Level Order Traversal Video Tutorial

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.