CC-15 : : Implement DFS Pre-order search.
Description:
Given an input integer, do a Depth First Pre-order search to check if that integer exists in any of the Binary Tree node’s node data.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
Search:78 Search:43 |
9 Found? true 78 Found? true 43 Found? false |
Pseudocode:
| Initialize a Stack to temporarily hold Binary Tree Nodes that are being processed in LIFO order. |
| Add the root node of Binary Tree to the Stack. |
| Iterate through stack nodes using an while loop, while Stack size is not zero:
Extract the first node of stack and assign it to a variable named parentNode.
If parentNode’s node data is equal to integer to be searched, return true.
If the parentNode’s right child is not null, add it the right child node to the Stack.
If the parentNode’s left child is not null, add it the left child node to the Stack.
|
Code:
public boolean dfPreOrderSearch(BinTreeNode root, int toSearch) throws Exception{
if (root==null) {return false;}
Deque<BinTreeNode> stack=new LinkedList<BinTreeNode>();
stack.offerFirst(root);
BinTreeNode parent=null;
while (stack.size()!=0) {
parent=stack.pollFirst();
if (parent.getNodeData()==toSearch) {
return true;
}
if (parent.getRightChild()!=null) {
stack.offerFirst(parent.getRightChild());
}
if (parent.getLeftChild()!=null) {
stack.offerFirst(parent.getLeftChild());
}
}
return false;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |