C# || How To Traverse Bottom Up Binary Tree Level Order Using C#

Print Friendly, PDF & Email

The following is a module with functions which demonstrates how to traverse bottom up binary tree level order using C#.


1. Level Order Bottom – Problem Statement

Given the root of a binary tree, return the bottom-up level order traversal of its nodes’ values. (i.e., from left to right, level by level from leaf to root).

Example 1:

Example 1


Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]

Example 2:


Input: root = [1]
Output: [[1]]

Example 3:


Input: root = []
Output: []


2. Level Order Bottom – Solution

The following is a solution which demonstrates how to traverse bottom up binary tree level order.

The idea of this solution is to have a result list which keeps track of the items found on each level. A variable is also used to keep track of the maximum depth levels in the tree. The max depth level is used to insert node values into their appropriate result list slot.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


[[15,7],[9,20],[3]]
[[1]]
[]

Was this article helpful?
👍 YesNo

Leave a Reply