Note that there are some explanatory texts on larger screens.

plurals
  1. POCan't print elements of BST at a given level in reverse order
    primarykey
    data
    text
    <p>I am trying to write a code, which, given a Binary Search Tree root and a level, prints out the elements of the tree at that level. This is working fine:</p> <pre><code>def myprint(root,level): if root: if not level: print root.data, else: myprint(root.left,level-1) myprint(root.right,level-1) </code></pre> <p>However, when I try to tweak it to print the elements at a level in reverse order, it dosn't work. For the following tree:</p> <pre><code> 26 / \ 13 39 / \ / \ 6 19 32 51 / \ / \ / \ / \ 4 8 14 31 33 68 \ 17 </code></pre> <p>if I want to output the elements at level 3 (level of root is 0) from right to left, the output should be <code>68 33 31 14 8 4</code>. The code above does the reverse correctly, that is, prints out <code>4 8 14 31 33 68</code>. But the below code doesn't print the reverse order correctly, and prints out <code>31 33 68 4 8 14</code> instead:</p> <pre><code>def revprint(root,level): if root: if not level: print root.data, else: myprint(root.right,level-1) myprint(root.left,level-1) </code></pre> <p>Can anybody spot the error, and tell me how to rectify it? The code for initializing the tree is as follows:</p> <pre><code>class tree: def __init__(self,data): self.data = data self.successor,self.left,self.right = None,None,None def push(self,data): root = self while root: oldroot = root if root.data &gt; data: root = root.left elif root.data &lt; data: root = root.right if data &gt; oldroot.data: oldroot.right = tree(data) else: oldroot.left = tree(data) a = tree(26) for x in [13,39,6,19,4,8,5,10,9,14,17,15,32,51,68,31,33,36,34]: a.push(x) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload