The simple answer is.. Just change the queue to a stack! (assuming it's a binary tree)
If you want to traverse from left to right you should invert the order of the pushes (like I did):
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);
}
So.. This will traverse the tree:
in the order:
A -> B -> D -> E -> C -> F -> G
The order of operations will be:
- push(a)
- pop ; a
- push(c)
- push(b)
- pop ; b
- push(e)
- push(d)
- pop ; d
- pop ; e
- pop ; c
- push(g)
- push(f)
- pop f
- pop g
Another way
There's a similar way using recursion (it will be like using an implicit stack)
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