Created
July 5, 2016 01:18
-
-
Save meghakrishnamurthy/499c5ba23c301aa1eb4f8a87f063bc6e to your computer and use it in GitHub Desktop.
Depth First Search of a binary tree - Java implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package megha.codingproblem.trees; | |
import java.util.Stack; | |
/** | |
* Git repo link - https://github.com/meghakrishnamurthy/CodingProblems/blob/master/src/megha/codingproblem/trees/DepthFirstSearch.java | |
* | |
* Depth first search implementation using a Stack | |
* | |
* Time complexity - O(n) | |
* Space complexity - Best/Average case O(1) and worst case O(n) | |
* @author megha krishnamurthy | |
* | |
*/ | |
public class DepthFirstSearch { | |
/** | |
* This method performs a depth first search on a binary tree | |
* @param root | |
*/ | |
public void depthFirstSearch(Node root) { | |
if(root == null) { | |
return; | |
} | |
Stack<Node> nodeStack = new Stack<Node>(); | |
nodeStack.push(root); | |
while(!nodeStack.isEmpty()) { | |
Node node = nodeStack.pop(); | |
System.out.print(node.data + " "); | |
if(node.right != null) { | |
nodeStack.push(node.right); | |
} | |
if(node.left != null) { | |
nodeStack.push(node.left); | |
} | |
} | |
} | |
public static void main(String args[]) { | |
Node root = new Node(10); | |
root.left = new Node(6); | |
root.right = new Node(21); | |
root.left.left = new Node(1); | |
root.left.right = new Node(8); | |
root.right.left = new Node(13); | |
root.right.right = new Node(25); | |
root.right.left.left = new Node (12); | |
root.right.left.right = new Node(18); | |
DepthFirstSearch dfs = new DepthFirstSearch(); | |
dfs.depthFirstSearch(root); | |
} | |
} | |
private class Node { | |
int data; | |
Node left; | |
Node right; | |
private Node(int value) { | |
data = value; | |
left = right = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment