Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The simple answer is.. Just change the queue to a stack! (assuming it's a binary tree)</p> <p>If you want to traverse from left to right you should invert the order of the pushes (like I did):</p> <pre><code>stack.push(rootNode); while(stack.Any()) { var currentNode = stack.pop(); if(currentNode.data == searchedData) break; if(currentNode.Right != null) stack.push(currentNode.Right); if(currentNode.Left != null) stack.push(currentNode.Left); } </code></pre> <p>So.. This will traverse the tree:</p> <p><img src="https://i.stack.imgur.com/ewxAr.jpg" alt="enter image description here"></p> <p>in the order:</p> <p>A -> B -> D -> E -> C -> F -> G</p> <p>The order of operations will be:</p> <ol> <li>push(a)</li> <li>pop ; a</li> <li>push(c)</li> <li>push(b)</li> <li>pop ; b</li> <li>push(e)</li> <li>push(d)</li> <li>pop ; d</li> <li>pop ; e</li> <li>pop ; c</li> <li>push(g)</li> <li>push(f)</li> <li>pop f</li> <li>pop g</li> </ol> <h1>Another way</h1> <p>There's a similar way using recursion (it will be like using an implicit stack)</p> <pre class="lang-py prettyprint-override"><code>def dfsSearch(node, searchedData): # Base case 1: end of the tree if node == None: return None # Base case 2: data found if node.data == searchedData: return node # Recursive step1: Traverse left child left = dfsSearch(node.left, searchedData) if left != None: return left # Recursive step2: Traverse right child right = dfsSearch(node.right, searchedData) if right != None: return right return None </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.
 

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