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

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

1 min read 181 words
1 min read
ShareWhatsAppPost on X
  • 1The algorithm performs a bottom-up level order traversal of a binary tree's nodes from leaf to root.
  • 2It utilizes a queue for breadth-first traversal and a stack to reverse the order of levels.
  • 3The time complexity is O(n) and the space complexity is O(1) in the worst case.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The algorithm performs a bottom-up level order traversal of a binary tree's nodes from leaf to root."

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)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 6 October 2020 · 1 min read · 181 words

Part of AskGif Blog · coding

You might also like

Binary Tree Level Order Traversal II - Tree - Easy - LeetCode | AskGif Blog