{"id":4850,"date":"2023-06-27T18:44:53","date_gmt":"2023-06-27T13:14:53","guid":{"rendered":"https:\/\/www.interviewbit.com\/blog\/?p=4850"},"modified":"2023-06-27T18:56:28","modified_gmt":"2023-06-27T13:26:28","slug":"reverse-level-order-traversal","status":"publish","type":"post","link":"https:\/\/www.interviewbit.com\/blog\/reverse-level-order-traversal\/","title":{"rendered":"Reverse Level Order Traversal"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<div class=\"gutentoc tocactive nostyle\"><div class=\"gutentoc-toc-wrap\"><div class=\"gutentoc-toc-title-wrap\"><div class=\"gutentoc-toc-title\">Table Of Contents<\/div><div id=\"open\" class=\"text_open\">show<\/div><\/div><div id=\"toclist\"><div class=\"gutentoc-toc__list-wrap\"><ul class=\"gutentoc-toc__list\"><li><a href=\"#problem-statement\">Problem Statement<\/a><\/li><li><a href=\"#approach-1-recursive-dfs\">Approach 1: Recursive DFS<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-code-implementation\">C++ Code Implementation<\/a><\/li><li><a href=\"#java-code-implementation\">Java Code Implementation<\/a><\/li><li><a href=\"#python-code-implementation\">Python Code Implementation<\/a><\/li><\/ul><li><a href=\"#approach-2-iteration-bfs\">Approach 2: Iteration: BFS<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-code-implementation\">C++ Code Implementation<\/a><\/li><li><a href=\"#java-code-implementation\">Java Code Implementation<\/a><\/li><li><a href=\"#python-code-implementation\">Python Code Implementation<\/a><\/li><\/ul><li><a href=\"#practice-question\">Practice Question:<\/a><\/li><li><a href=\"#faqs\">FAQs<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#q1-how-to-iteratively-solve-the-problem\">Q.1: How to iteratively solve the problem?<\/a><\/li><li><a href=\"#q2-what-is-the-most-efficient-approach-to-solving-this-problem\">Q.2: What is the most efficient approach to solving this problem?<\/a><\/li><\/ul><\/ul><\/div><\/div><\/div><\/div>\n\n\n\n<h2 id=\"problem-statement\">Problem Statement<\/h2>\n\n\n\n<p>Given a binary tree, return the reverse level order traversal of its nodes\u2019 values. (i.e, from left to right and from the last level to starting level).<\/p>\n\n\n\n<p><strong>Examples:<\/strong><br><strong>Input:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large is-resized\"><img  loading=\"lazy\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-5032 pk-lazyload\"  width=\"545\"  height=\"387\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 545px) 100vw, 545px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-1024x727.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-1024x727.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-300x213.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-768x545.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-380x270.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-550x391.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-800x568.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-1160x824.png 1160w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input.png 1221w\" ><\/figure><\/div>\n\n\n\n<p><strong>Output:<\/strong> [15, 7, 9, 20, 3]<br><strong>Explanation:<\/strong><\/p>\n\n\n\n<ul><li>Nodes as level 3 : [15, 7]<\/li><li>Nodes at level 2: [9, 20]<\/li><li>Nodes at level 1: [3]<\/li><li>Reverse level order traversal will be: [15, 7, 9, 20, 3]<\/li><\/ul>\n\n\n\n<p><strong>Input:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large is-resized\"><img  loading=\"lazy\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-5033 pk-lazyload\"  width=\"593\"  height=\"420\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 593px) 100vw, 593px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input2-1024x727.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input2-1024x727.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input2-300x213.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input2-768x545.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input2-380x270.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input2-550x391.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input2-800x568.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input2-1160x824.png 1160w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input2.png 1221w\" ><\/figure><\/div>\n\n\n\n<p><strong>Output:<\/strong> [3, 6, 2, 1]\n\n\n\n<h2 id=\"approach-1-recursive-dfs\">Approach 1: Recursive DFS<\/h2>\n\n\n\n<p>The idea is to apply the recursive approach to solve the problem.<\/p>\n\n\n\n<p><strong>Algorithm<\/strong><\/p>\n\n\n\n<ul><li>The recursive function <strong>helper <\/strong>takes two parameters, <strong>node <\/strong>and <strong>levels <\/strong>i.e. the current node and its level.<\/li><li>Ensure that the tree is not empty.<\/li><li>In the output list <strong>levels<\/strong>, compare the size of <strong>levels<\/strong> to <strong>node <\/strong>level.<\/li><li>Append the value of the current node to the <strong>node level<\/strong>.<\/li><li>If the current node contains children nodes, recursively traverse, <strong>helper(node -&gt; left \/ node -&gt; right, level + 1)<\/strong>.<\/li><\/ul>\n\n\n\n<h3 id=\"c-code-implementation\"><span id=\"c-code-implementation-2\">C++ Code Implementation<\/span><\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">void levelOrder(vector &lt; vector &lt; int >> &amp; ans, TreeNode * node, int level) {\n  if (!node) return;\n  if (level >= ans.size())\n    ans.push_back({});\n  ans[level].push_back(node -> val);\n  levelOrder(ans, node -> left, level + 1);\n  levelOrder(ans, node -> right, level + 1);\n}\n \nvector &lt; vector &lt; int >> levelOrderBottom(TreeNode * root) {\n  vector &lt; vector &lt; int >> ans;\n  levelOrder(ans, root, 0);\n  reverse(ans.begin(), ans.end());\n  return ans;\n}<\/pre>\n\n\n\n<h3 id=\"java-code-implementation\"><span id=\"java-code-implementation-2\">Java Code Implementation<\/span><\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"> class Solution {\n  List &lt; List &lt; Integer >> levels = new ArrayList &lt; List &lt; Integer >> ();\n \n  public void helper(TreeNode node, int level) {\n    if (levels.size() == level)\n      levels.add(new ArrayList &lt; Integer > ());\n \n    levels.get(level).add(node.val);\n    if (node.left != null)\n      helper(node.left, level + 1);\n    if (node.right != null)\n      helper(node.right, level + 1);\n  }\n  public List &lt; List &lt; Integer >> levelOrderBottom(TreeNode root) {\n    if (root == null) return levels;\n    helper(root, 0);\n    Collections.reverse(levels);\n    return levels;\n  }\n}<\/pre>\n\n\n\n<h3 id=\"python-code-implementation\"><span id=\"python-code-implementation-2\">Python Code Implementation<\/span><\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Solution:\n    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:\n        levels = []\n        if not root:\n            return levels\n \n        def helper(node, level):\n            if len(levels) == level:\n                levels.append([])\n \n            levels[level].append(node.val)\n            if node.left:\n                helper(node.left, level + 1)\n            if node.right:\n                helper(node.right, level + 1)\n \n        helper(root, 0)\n        return levels[::-1]<\/pre>\n\n\n\n<ul><li><strong>Time Complexity:<\/strong> O(N), where N is the number of nodes.<\/li><li><strong>Space Complexity:<\/strong> O(N), for recursion stack.<\/li><\/ul>\n\n\n\n<h2 id=\"approach-2-iteration-bfs\">Approach 2: Iteration: BFS<\/h2>\n\n\n\n<p>With a similar idea of recursive traversal, the problem can also be solved using an iterative approach.<\/p>\n\n\n\n<p><strong>Algorithm<\/strong><\/p>\n\n\n\n<ul><li>Initialise two queues. The first queue is to determine the current level and the second queue is to determine the next level.<\/li><li>While the next level queue is not empty, perform the following:<ul><li>Currentlevel =&nbsp; nextlevel<\/li><li>Empty nextlevel queue<\/li><li>Traverse through the current level queue and add the value of the node in the final list.<\/li><li>Push the left and right child(if it exists) in the queue.<\/li><\/ul><\/li><li>Reverse the levels.<\/li><\/ul>\n\n\n\n<h3 id=\"c-code-implementation\">C++ Code Implementation<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">vector &lt; vector &lt; int >> levelOrderBottom(TreeNode * root) {\n  vector &lt; vector &lt; int >> v;\n  if (root == nullptr)\n    return {};\n \n  queue &lt; TreeNode * > q;\n  q.push(root);\n \n  while (q.empty() == false) {\n    vector &lt; int > res;\n    int len = q.size();\n    for (int i = 0; i &lt; len; i++) {\n      TreeNode * curr = q.front();\n      q.pop();\n \n      res.push_back(curr -> val);\n \n      if (curr -> left)\n        q.push(curr -> left);\n      if (curr -> right)\n        q.push(curr -> right);\n    }\n    v.push_back(res);\n  }\n  reverse(v.begin(), v.end());\n  return v;\n}<\/pre>\n\n\n\n<h3 id=\"java-code-implementation\">Java Code Implementation<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"> class Solution {\n  public List &lt; List &lt; Integer >> levelOrderBottom(TreeNode root) {\n    List &lt; List &lt; Integer >> levels = new ArrayList &lt; List &lt; Integer >> ();\n    if (root == null) return levels;\n \n    ArrayDeque &lt; TreeNode > nextLevel = new ArrayDeque() {\n      {\n        offer(root);\n      }\n    };\n    ArrayDeque &lt; TreeNode > currLevel = new ArrayDeque();\n \n    while (!nextLevel.isEmpty()) {\n      currLevel = nextLevel.clone();\n      nextLevel.clear();\n      levels.add(new ArrayList &lt; Integer > ());\n \n      for (TreeNode node: currLevel) {\n        levels.get(levels.size() - 1).add(node.val);\n        if (node.left != null)\n          nextLevel.offer(node.left);\n        if (node.right != null)\n          nextLevel.offer(node.right);\n      }\n    }\n \n    Collections.reverse(levels);\n    return levels;\n  }\n}<\/pre>\n\n\n\n<h3 id=\"python-code-implementation\">Python Code Implementation<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">MAX_CHAR = 26\nclass Solution:\n    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:\n        levels = []\n        next_level = deque([root])\n \n        while root and next_level:\n            curr_level = next_level\n            next_level = deque()\n            levels.append([])\n \n            for node in curr_level:\n                levels[-1].append(node.val)\n                if node.left:\n                    next_level.append(node.left)\n                if node.right:\n                    next_level.append(node.right)\n \n        return levels[::-1]<\/pre>\n\n\n\n<ul><li><strong>Time Complexity:<\/strong> O(N),\u00a0 where N is the number of nodes.<\/li><li><strong>Space Complexity:<\/strong> O(N), since the queue is used.<\/li><\/ul>\n\n\n\n<h2 id=\"practice-question\">Practice Question:<\/h2>\n\n\n\n<ul><li><a rel=\"noreferrer noopener\" href=\"https:\/\/www.interviewbit.com\/problems\/reverse-level-order\/\" target=\"_blank\">Reverse Level Order<\/a><\/li><\/ul>\n\n\n\n<h2 id=\"faqs\">FAQs<\/h2>\n\n\n\n<h3 id=\"q1-how-to-iteratively-solve-the-problem\"><span id=\"q-1-how-to-iteratively-solve-the-problem\">Q.1: How to iteratively solve the problem?<\/span><\/h3>\n\n\n\n<p><strong>Ans.<\/strong> We use two queues, one for the current level and another for the next level. For each level, iteratively traverse over the tree and keep pushing the node values inside the queues. In the end, reverse the final list.<\/p>\n\n\n\n<h3 id=\"q2-what-is-the-most-efficient-approach-to-solving-this-problem\"><span id=\"q-2-what-is-the-most-efficient-approach-to-solving-this-problem\">Q.2: What is the most efficient approach to solving this problem?<\/span><\/h3>\n\n\n\n<p><strong>Ans. <\/strong>Both recursive and iterative DFS and BFS are the most efficient approaches to solving the problem. The time complexity is O(N) and the space complexity is O(N).<\/p>\n","protected":false},"excerpt":{"rendered":"Problem Statement Given a binary tree, return the reverse level order traversal of its nodes\u2019 values. (i.e, from&hellip;\n","protected":false},"author":5,"featured_media":5031,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_daextam_enable_autolinks":"1","csco_singular_sidebar":"","csco_page_header_type":"","csco_appearance_grid":"","csco_page_load_nextpost":"","csco_post_video_location":[],"csco_post_video_location_hash":"","csco_post_video_url":"","csco_post_video_bg_start_time":0,"csco_post_video_bg_end_time":0},"categories":[145],"tags":[676],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4850"}],"collection":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/comments?post=4850"}],"version-history":[{"count":8,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4850\/revisions"}],"predecessor-version":[{"id":20918,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4850\/revisions\/20918"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media\/5031"}],"wp:attachment":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media?parent=4850"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/categories?post=4850"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/tags?post=4850"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}