{"id":1860,"date":"2024-03-06T21:00:00","date_gmt":"2024-03-06T21:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1860"},"modified":"2024-03-08T09:00:42","modified_gmt":"2024-03-08T09:00:42","slug":"binary-tree-right-side-view","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/binary-tree-right-side-view\/","title":{"rendered":"Print Right Side View of Binary Tree (with code)"},"content":{"rendered":"\n<p>A tree is a commonly used data structure that helps us to store and efficiently retrieve data. There are many technical questions asked in interviews.  In this article, we will discuss one such problem where we have to print the Right Side View of a Binary Tree and implement the programs in different languages.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Binary Tree Right Side View Problem<\/strong><\/h2>\n\n\n\n<p><strong>In the Binary Tree Right Side View problem, we are given a binary tree and we have to return the right view of the binary tree i.e., if we stand on the right side of the tree we have to return the nodes we can see. <\/strong><\/p>\n\n\n\n<p>Let\u2019s try to understand this with an example:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter is-resized\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/ZvRQFQFN90qSFnwoK481mSgiMGCVpBWj7Ss9buWXwoWYTe2hQXyg_D5_cdxkX7Enc-VwllzAn33BSYA7OpmfbB3kvaIC0xCB036aQ913FA-Yv8TOVZxcHTrKHgrO1rKze_3TD1NSG7P7xMhh7IJE0q0\" alt=\"Right Side View of Binary Tree\" style=\"width:898px;height:auto\"\/><\/figure>\n<\/div>\n\n\n<p>Values you can see are highlighted in the tree from the right side.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/Jt2BaehemzOA9_Bb9oajhQbSHJkeriSVmYkwdkW_xVi2yL4kd21htvnPhRoKWSD8RhOvL_CsEaoPLRTDOhknCQbkeIHmnRcRBURlHqeYNXL3TyYrCZ9RRUZ3is-T6j3g03aak730xX7bCD4eeV1JD48\" alt=\"Right Side Views nodes\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Iterative Method<\/strong><\/h2>\n\n\n\n<p>In the iterative method, we will iterate through each level and then push the rightmost element into our resultant array. This can be accomplished by utilizing a queue data structure. We choose a queue because we will be inserting elements at the back and removing the topmost element.&nbsp;<\/p>\n\n\n\n<p>Here is the process step-by-step:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Create a queue that stores the address of each node of the tree.&nbsp;<\/li>\n\n\n\n<li>Push the root into the queue and a Null value.<\/li>\n\n\n\n<li>Now iterate over the queue till it is not empty. Make a variable name sz which stores the current size of the queue.<\/li>\n\n\n\n<li>Iterate a loop of size sz.&nbsp;<\/li>\n\n\n\n<li>Check if the value of the next element in the queue is Null, then push the current value into the resultant array as this would be the rightmost element at any level.<\/li>\n\n\n\n<li>If the value is null simply pop this element and move to the next one by pushing a null value into the queue.<\/li>\n\n\n\n<li>If not, then push its left and right values if exist.<\/li>\n\n\n\n<li>Return the resultant array once all iterations are done.<\/li>\n<\/ol>\n\n\n\n<p>The time complexity for the above method is O(n) as we are iterating over the tree. Here n is the total number of nodes in the tree. Space complexity is O(n) as we are storing all values in a level in the queue.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Recursive Method<\/strong><\/h2>\n\n\n\n<p><strong>We can print the right-side view of a binary tree using recursion. <\/strong>We will first check if the current level of the node is the same as our size, then push this node value into the vector. <\/p>\n\n\n\n<p>Now, we recursively call the right node of the current node by increasing the level and then the left node of the current node. We repeat the same process until we find the final bottom node on the right side.<\/p>\n\n\n\n<p> This works because we first check all the right nodes and then the left ones, and if the level is the same as our size, then only we push the value into our array. You can check more <a href=\"https:\/\/favtutor.com\/blogs\/recursion-vs-iteration\">differences between iteration and recursion<\/a> here.<\/p>\n\n\n\n<p>Let\u2019s understand this with an example:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/i33fC9BWhSv6_SRHNEUpuBAlPR3jisRMYH-DqBp1JtlsSXWwoKht8ADUKHiANUgguGPGkB6-lWIYtTO9vD0ne9ooCx3bxJUql8FeYTPlzRXGry7ZLifm8wWR5-sNh3k-PTRQjd8KGlYkkOLKs4sBP4g\" alt=\"Input Binary Tree tree\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>At first, we have root as a first element in level 0 so we will push this into our array<\/li>\n\n\n\n<li>Next, we will move to node 3 as this is of level 1 and our array size is also 1, so we will push this into our array.<\/li>\n\n\n\n<li>Next, we will move to node 2, this is of level 1 and our array size is 2 so we will not push this into the array.<\/li>\n\n\n\n<li>Next, we will be at node 4, which is of level 2 and the size of the array is also 2, so we will push this into the array.<\/li>\n\n\n\n<li>Finally, we have Node 5. It is at level 3, and the size of the array is also 3. Therefore, we will push this value into the array.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/C42rtfPnsaCQ6Ekvasq2U1-ltyiuVDhjXkH6TX11xgmLPvEd1Us2A1ItpInLnay2dkROwWx-Fm2iBadXEVfO5hn4a15GWtPUI_MDMKWutcEGj76-179AkG6kLnCMPW0xjC9vm5C4lxXpayoy4D__DxE\" alt=\"Explanation\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Now all nodes are done, return this array.<\/li>\n<\/ul>\n\n\n\n<p>Let&#8217;s now move to code it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Below is the C++ program to print the right view of the binary tree:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include&lt;bits\/stdc++.h&gt;\nusing namespace std;\n\n\nclass node{\n    public:\n    int value;\n    node* left;\n    node* right;\n\n    node(int a){\n        value = a;\n        left = NULL;\n        right = NULL;\n    }\n};\n\nvoid right_view(node* root, int level, vector&lt;int&gt;&amp; arr){\n    if(root== NULL) return;\n    int n = arr.size();\n    if(n==level) arr.push_back(root-&gt;value);\n    \/\/calling right side first.\n    right_view(root-&gt;right, level + 1, arr);\n    \/\/calling left side.\n    right_view(root-&gt;left, level + 1,arr);\n    return;\n}\n\n\nint main(){\n    \n    node* root =  new node(1);\n    root-&gt;left =  new node(2);\n    root-&gt;right = new node(3);\n    root-&gt;left-&gt;left = new node(4);\n    root-&gt;left-&gt;right =  new node(5);\n    root-&gt;left-&gt;right-&gt;left = new node(6);\n\n    \/\/an array.\n    vector&lt;int&gt;ans;\n    \/\/ calling function right_view.\n    right_view(root,0,ans);\n\n    \/\/ printing values in the array.\n    for(int i=0;i&lt;ans.size();i++){\n        cout&lt;&lt;ans[i]&lt;&lt;&quot; &quot;;\n    }\n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>We can implement the code in Java also:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">import java.util.ArrayList;\n\nclass Node {\n    int value;\n    Node left;\n    Node right;\n\n    Node(int a) {\n        value = a;\n        left = null;\n        right = null;\n    }\n}\n\npublic class Main {\n    static void rightView(Node root, int level, ArrayList&lt;Integer&gt; arr) {\n        if (root == null)\n            return;\n        int n = arr.size();\n        if (n == level)\n            arr.add(root.value);\n        \/\/ calling right side first.\n        rightView(root.right, level + 1, arr);\n        \/\/ calling left side.\n        rightView(root.left, level + 1, arr);\n    }\n\n    public static void main(String[] args) {\n        Node root = new Node(1);\n        root.left = new Node(2);\n        root.right = new Node(3);\n        root.left.left = new Node(4);\n        root.left.right = new Node(5);\n        root.left.right.left = new Node(6);\n\n        \/\/ ans array.\n        ArrayList&lt;Integer&gt; ans = new ArrayList&lt;&gt;();\n        \/\/ calling function rightView.\n        rightView(root, 0, ans);\n\n        \/\/ printing values in the array.\n        for (int i = 0; i &lt; ans.size(); i++) {\n            System.out.print(ans.get(i) + &quot; &quot;);\n        }\n    }\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>Here is the Python Solution for Binary Tree Right Side View problem:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">class Node:\n    def __init__(self, a):\n        self.value = a\n        self.left = None\n        self.right = None\n\ndef right_view(root, level, arr):\n    if root is None:\n        return\n    n = len(arr)\n    if n == level:\n        arr.append(root.value)\n    # calling right side first.\n    right_view(root.right, level + 1, arr)\n    # calling left side.\n    right_view(root.left, level + 1, arr)\n\nif __name__ == &quot;__main__&quot;:\n    root = Node(1)\n    root.left = Node(2)\n    root.right = Node(3)\n    root.left.left = Node(4)\n    root.left.right = Node(5)\n    root.left.right.left = Node(6)\n\n    # ans array.\n    ans = []\n    # calling function right_view.\n    right_view(root, 0, ans)\n\n    # printing values in the array.\n    for val in ans:\n        print(val, end=&quot; &quot;)<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-6c88c0d9cbd547375113aa3a47091638\" style=\"background-color:#fedcba\"><code>1 3 5 6<\/code><\/pre>\n\n\n\n<p>The time complexity to print the right side view of a binary tree using recursion is O(n) where n is the total number of nodes. The space complexity will also be O(n) since we are recursively traversing each node.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion&nbsp;<\/strong><\/h2>\n\n\n\n<p>In this article, we explore how we can print the right side view of a binary tree using iteration and recursion. This problem can also be found in <a href=\"https:\/\/leetcode.com\/problems\/binary-tree-right-side-view\/description\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">leetcode<\/a>. Recursion decreases both time and space complexity to some extent.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Find out how to print the right side view of a binary tree, a leetcode problem, using iteration and recursion, with implementation in C++, Java, and Python.<\/p>\n","protected":false},"author":14,"featured_media":1862,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-1860","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1860","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1860"}],"version-history":[{"count":4,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1860\/revisions"}],"predecessor-version":[{"id":2259,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1860\/revisions\/2259"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1862"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1860"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1860"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1860"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}