Blogs Hub

by Sumit Chourasia | Oct 06, 2020 | Category :coding | Tags : algorithm binary-tree data-structure easy leetcode tree

Binary Tree Level Order Traversal II - Tree - Easy - LeetCode

Binary Tree Level Order Traversal II - Tree - Easy - LeetCode

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

For example:
Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
return its bottom-up level order traversal as:
[
  [15,7],
  [9,20],
  [3]
]

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    public IList<IList<int>> LevelOrderBottom(TreeNode root) {        
        var result = new List<IList<int>>();
        var queue = new Queue<TreeNode>();
        var stack = new Stack<IList<int>>();
        if(root == null){
            return result;
        }
        
        queue.Enqueue(root);
        while(queue.Count()>0){
            int count = queue.Count();
            var innerRes = new List<int>();
            while(count-->0){
                var temp = queue.Dequeue();
                innerRes.Add(temp.val);
                if(temp.left != null){
                    queue.Enqueue(temp.left);
                }
                if(temp.right != null){
                    queue.Enqueue(temp.right);
                }
            }
            stack.Push(innerRes);
        }
        
        while(stack.Count()>0){
            result.Add(stack.Pop());
        }
        
        return result;
    }
}

Time Complexity: O(n) in the worst case

Space Complexity: O(1)