Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>What about this approach: Traverse the tree in preorder (visiting each node). For each node (when travelled to it) check if it has a left child. If so (indicating a node with child elements in original tree) print the nodes data with a ':' and take its subtree and follow all right sons (which are representing all siblings) recursively, afterwards print each right sons data (you have it in reversed order. In Code:</p> <pre><code>void print_siblings() { if (this-&gt;right != NULL) { this-&gt;right-&gt;print_siblings(); } cout &lt;&lt; data &lt;&lt; ", "; } void traverse(void) { if (this-&gt;left != NULL) { cout &lt;&lt; data &lt;&lt; ":"; this-&gt;left-&gt;print_siblings(); cout &lt;&lt; endl; this-&gt;left-&gt;traverse(); } if (this-&gt;right != NULL) { this-&gt;right-&gt;traverse(); } } </code></pre> <p>Edit: Here is a inorder-traversal:</p> <pre><code>void traverse_inorder(void) { if (this-&gt;left != NULL) { this-&gt;left-&gt;traverse_inorder(); cout &lt;&lt; data &lt;&lt; ":"; this-&gt;left-&gt;print_siblings(); cout &lt;&lt; endl; } if (this-&gt;right != NULL) { this-&gt;right-&gt;traverse_inorder(); } } </code></pre> <p>Output for preorder would be:</p> <pre><code>1:5, 4, 3, 2, 3:7, 6, 5:8, 8:11, 10, 9, </code></pre> <p>Output for inorder would be:</p> <pre><code>3:7, 6, 8:11, 10, 9, 5:8, 1:5, 4, 3, 2, </code></pre> <p>Edit2: Just for completeness, the post-order traversal as well :-)</p> <pre><code>void traverse_postorder(void) { if (this-&gt;left != NULL) { this-&gt;left-&gt;traverse_postorder(); } if (this-&gt;right != NULL) { this-&gt;right-&gt;traverse_postorder(); } if (this-&gt;left != NULL) { cout &lt;&lt; data &lt;&lt; ":"; this-&gt;left-&gt;print_siblings(); cout &lt;&lt; endl; } } </code></pre> <p>And its output:</p> <pre><code>8:11, 10, 9, 5:8, 3:7, 6, 1:5, 4, 3, 2, </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