{"id":2266,"date":"2023-06-12T17:26:55","date_gmt":"2023-06-12T11:56:55","guid":{"rendered":"https:\/\/www.interviewbit.com\/blog\/?p=2266"},"modified":"2023-06-12T17:28:09","modified_gmt":"2023-06-12T11:58:09","slug":"preorder-traversal","status":"publish","type":"post","link":"https:\/\/www.interviewbit.com\/blog\/preorder-traversal\/","title":{"rendered":"Preorder 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=\"#1-recursive-approach\">1. Recursive Approach<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#implementation-of-recursive-approach\">Implementation of Recursive Approach<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-implementation\">C++ Implementation<\/a><\/li><li><a href=\"#java-implementation\">Java Implementation<\/a><\/li><li><a href=\"#python-implementation\">Python Implementation<\/a><\/li><\/ul><\/ul><li><a href=\"#2-iterative-approach\">2. Iterative Approach<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#implementation-of-iterative-approach\">Implementation of Iterative Approach<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-implementation-of-iterative-approach\">C++ Implementation of Iterative Approach<\/a><\/li><li><a href=\"#java-implementation-of-iterative-approach\">Java Implementation of Iterative Approach<\/a><\/li><li><a href=\"#python-implementation-of-iterative-approach\">Python Implementation of Iterative Approach<\/a><\/li><\/ul><\/ul><li><a href=\"#practice-questions\">Practice Questions<\/a><\/li><li><a href=\"#frequently-asked-questions\">Frequently Asked Questions<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#q1-is-there-any-way-to-print-the-preorder-traversal-in-o1-space-including-function-call-stack\">Q.1: Is there any way to print the preorder traversal in O(1) space (Including function call stack)?<\/a><\/li><li><a href=\"#q2-can-we-write-preorder-traversal-from-inorder-and-postorder-traversal\">Q.2: Can we write preorder traversal from Inorder and Postorder traversal?<\/a><\/li><li><a href=\"#q3-is-preorder-sufficient-to-maintain-the-structure-of-the-tree\">Q.3: Is Preorder sufficient to maintain the structure of the tree?<\/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, the task is to print the preorder traversal of the tree.<\/p>\n\n\n\n<p>Pre-Order is a way to traverse the binary tree in which our directions are fixed <\/p>\n\n\n\n<p>i.e. <strong>root-> left &#8211; > right<\/strong>. It means first we will traverse the root of the tree and then go to its left subtree and after traversing that subtree we will move to its right part of the subtree.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img  loading=\"lazy\"  width=\"1024\"  height=\"500\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"Example\"  class=\"wp-image-2270 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-2-1.jpg\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-2-1.jpg 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-2-1-300x146.jpg 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-2-1-768x375.jpg 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-2-1-380x186.jpg 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-2-1-550x269.jpg 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-2-1-800x391.jpg 800w\" ><\/figure>\n\n\n\n<p>Example:<\/p>\n\n\n\n<ul><li><strong>Input:<\/strong> [A,B,C,D,E,F,G,NULL,NULL,NULL,NULL]<\/li><li><strong>Output:<\/strong> [A,B,DE,C,F,G]<\/li><\/ul>\n\n\n\n<p><strong>Explanation:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img  loading=\"lazy\"  width=\"1024\"  height=\"500\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-2271 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-3-1.jpg\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-3-1.jpg 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-3-1-300x146.jpg 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-3-1-768x375.jpg 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-3-1-380x186.jpg 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-3-1-550x269.jpg 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-3-1-800x391.jpg 800w\" ><\/figure>\n\n\n\n<ul><li><strong>Input:<\/strong> [1,2,3,4,5,6,7,-1,-1,-1,-1]<\/li><li><strong>Output:<\/strong> [1,2,4,5,3,6,7]<\/li><\/ul>\n\n\n\n<figure class=\"wp-block-image size-full\"><img  loading=\"lazy\"  width=\"1024\"  height=\"500\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-2269 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-1.jpg\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-1.jpg 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-1-300x146.jpg 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-1-768x375.jpg 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-1-380x186.jpg 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-1-550x269.jpg 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-1-800x391.jpg 800w\" ><\/figure>\n\n\n\n<h2 id=\"1-recursive-approach\">1. Recursive Approach<\/h2>\n\n\n\n<p>For implementing a recursive approach we first call the root of the current tree and then traverse the left and right subtree.<\/p>\n\n\n\n<h3 id=\"implementation-of-recursive-approach\">Implementation of Recursive Approach<\/h3>\n\n\n\n<h4 id=\"c-implementation\">C++ Implementation<\/h4>\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 printPreorder(struct Node* node)\n{\n    if (node == NULL)\n        return;\n \n    \/* first print data of node *\/\n    cout &lt;&lt; node->data &lt;&lt; \" \";\n \n    \/* then recur on left subtree *\/\n    printPreorder(node->left);\n \n    \/* now recur on right subtree *\/\n    printPreorder(node->right);\n}<\/pre>\n\n\n\n<h4 id=\"java-implementation\">Java Implementation<\/h4>\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=\"\">public List &lt; Integer > preorderTraversal(TreeNode root) {\n  List &lt; Integer > pre = new LinkedList &lt; Integer > ();\n  if (root == null) return pre;\n  pre.add(root.val);\n  pre.addAll(preorderTraversal(root.left));\n  pre.addAll(preorderTraversal(root.right));\n  return pre;\n}<\/pre>\n\n\n\n<h4 id=\"python-implementation\">Python Implementation<\/h4>\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=\"\">def printPreorder(root):\n \n    if root:\n \n        # First print the data of node\n        print(root.val),\n \n        # Then recur on left child\n        printPreorder(root.left)\n \n        # Finally recur on right child\n        printPreorder(root.right)<\/pre>\n\n\n\n<ul><li><strong>Time complexity:<\/strong> O(N), Where N is the size of the binary tree.<\/li><li><strong>Space complexity:<\/strong> O(1) If we don\u2019t consider the function call stack, else O(h), h is the height of the tree.<\/li><\/ul>\n\n\n\n<h2 id=\"2-iterative-approach\">2. Iterative Approach<\/h2>\n\n\n\n<p>The iterative approach uses stack data structure to print the preorder traversal. Follow the below steps.<\/p>\n\n\n\n<ul><li>Create an empty stack, Push the root node to the stack.<\/li><li>Do the following while the stack is not empty.<\/li><li>Pop an item from the stack and print it.<\/li><li>Push the right child of the popped item to stack.<\/li><li>Push the left child of the popped item to stack.<\/li><\/ul>\n\n\n\n<h3 id=\"implementation-of-iterative-approach\">Implementation of Iterative Approach<\/h3>\n\n\n\n<h4 id=\"c-implementation-of-iterative-approach\">C++ Implementation of Iterative Approach<\/h4>\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; int > preorderTraversal(TreeNode * root) {\n  stack &lt; TreeNode * > nodeStack;\n  vector &lt; int > result;\n  \/\/base case\n  if (root == NULL)\n    return result;\n  nodeStack.push(root);\n  while (!nodeStack.empty()) {\n    TreeNode * node = nodeStack.top();\n    result.push_back(node -> val);\n    nodeStack.pop();\n    if (node -> right)\n      nodeStack.push(node -> right);\n    if (node -> left)\n      nodeStack.push(node -> left);\n  }\n  return result;\n\n}<\/pre>\n\n\n\n<h4 id=\"java-implementation-of-iterative-approach\">Java Implementation of Iterative Approach<\/h4>\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=\"\">public List &lt; Integer > preorderTraversal(TreeNode node) {\n  List &lt; Integer > list = new LinkedList &lt; Integer > ();\n  Stack &lt; TreeNode > rights = new Stack &lt; TreeNode > ();\n  while (node != null) {\n    list.add(node.val);\n    if (node.right != null) {\n      rights.push(node.right);\n    }\n    node = node.left;\n    if (node == null &amp;&amp; !rights.isEmpty()) {\n      node = rights.pop();\n    }\n  }\n  return list;\n}<\/pre>\n\n\n\n<h4 id=\"python-implementation-of-iterative-approach\">Python Implementation of Iterative Approach<\/h4>\n\n\n\n<p><\/p>\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=\"\">def preorderTraversal(self, root):\n    ret = []\n    stack = [root]\n    while stack:\n        node = stack.pop()\n        if node:\n            ret.append(node.val)\n            stack.append(node.right)\n            stack.append(node.left)\n    return ret<\/pre>\n\n\n\n<ul><li><strong>Time complexity:<\/strong> O(N), Where N is the size of the binary tree.<\/li><li><strong>Space complexity:<\/strong> O(N)<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-black-background-color has-black-color is-style-wide\"\/>\n\n\n\n<h2 id=\"practice-questions\">Practice Questions<\/h2>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.interviewbit.com\/problems\/preorder-traversal\/\" target=\"_blank\">Preorder Traversal<\/a><br><a href=\"https:\/\/www.interviewbit.com\/problems\/valid-bst-from-preorder\/\" target=\"_blank\" rel=\"noreferrer noopener\">Valid BST from Preorder<\/a><\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-black-background-color has-black-color is-style-wide\"\/>\n\n\n\n<h2 id=\"frequently-asked-questions\">Frequently Asked Questions<\/h2>\n\n\n\n<h3 id=\"q1-is-there-any-way-to-print-the-preorder-traversal-in-o1-space-including-function-call-stack\"><span id=\"q-1-is-there-any-way-to-print-the-preorder-traversal-in-o1-space-including-function-call-stack\">Q.1: Is there any way to print the preorder traversal in O(1) space (Including function call stack)?<\/span><\/h3>\n\n\n\n<p>Ans: Yes, using Morris traversal.<\/p>\n\n\n\n<h3 id=\"q2-can-we-write-preorder-traversal-from-inorder-and-postorder-traversal\"><span id=\"q-2-can-we-write-preorder-traversal-from-inorder-and-postorder-traversal\">Q.2: Can we write preorder traversal from Inorder and Postorder traversal?<\/span><\/h3>\n\n\n\n<p>Ans: Yes.<\/p>\n\n\n\n<h3 id=\"q3-is-preorder-sufficient-to-maintain-the-structure-of-the-tree\"><span id=\"q-3-is-preorder-sufficient-to-maintain-the-structure-of-the-tree\">Q.3: Is Preorder sufficient to maintain the structure of the tree?<\/span><\/h3>\n\n\n\n<p>Ans: No, we need a Preorder and Inorder to find a unique structure.<\/p>\n","protected":false},"excerpt":{"rendered":"Problem Statement Given a binary tree, the task is to print the preorder traversal of the tree. Pre-Order&hellip;\n","protected":false},"author":5,"featured_media":2268,"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":[393],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/2266"}],"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=2266"}],"version-history":[{"count":4,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/2266\/revisions"}],"predecessor-version":[{"id":20046,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/2266\/revisions\/20046"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media\/2268"}],"wp:attachment":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media?parent=2266"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/categories?post=2266"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/tags?post=2266"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}