I have written a code to insert an element in a binary tree in java. Here are the functions to do the same:
public void insert(int data)
{
root = insert(root, data);
}
private Node insert(Node node, int data)
{
if (node == null)
node = new Node(data);
else
{
if (node.getRight() == null)
node.right = insert(node.right, data);
else
node.left = insert(node.left, data);
}
return node;
}
However when I traverse the tree, the answer I get is wrong. Here are the traversal functions (preorder):
public void preorder()
{
preorder(root);
}
private void preorder(Node r)
{
if (r != null)
{
System.out.print(r.getData() +" ");
preorder(r.getLeft());
preorder(r.getRight());
}
}
Okay so as suggested here's the definition for the Node class:
public class Node {
public int data;
public Node left, right;
/* Constructor */
public Node() {
left = null;
right = null;
data = 0;
}
/* Constructor */
public Node(int d, Node l, Node r) {
data = d;
left = l;
right = r;
}
//Constructor
public Node(int d) {
data = d;
}
/* Function to set link to next Node */
public void setLeft(Node l) {
left = l;
}
/* Function to set link to previous Node */
public void setRight(Node r) {
right = r;
}
/* Function to set data to current Node */
public void setData(int d) {
data = d;
}
/* Function to get link to next node */
public Node getLeft() {
return left;
}
/* Function to get link to previous node */
public Node getRight() {
return right;
}
/* Function to get data from current Node */
public int getData() {
return data;
}
}
I have re-checked the algorithm for traversal many times, and it's working perfectly. I believe the problem is in the insertion algorithm. Any suggestions?
If I understood correctly, you want to fill your binary tree in "layers". E.g. you want to put something into depth 4 only if depth 3 is "full binary tree".
Then the problem is whole logic of your insert algorithm that is DFS-based. In other words it inserts elements deeper and deeper on the one side instead of building full binary tree on both sides.
If you look closer to your insert algorithm you will see that once you skip "right" subtree, you will never return to it - even if the "left" subtree is already full binary tree. That leads to the tree that will be growing deeper and deeper on the left side but not growing on the right side.
Speaking in programming language. You do:
(node.right != null) && (node.left != null) => insert (node.left)
but you can't do this (start inserting node.left). What if node.left has both children and node.right has no children? You will attempt to insert to the left even you should do it in node.right.
So what you really need to do insertion BFS-based. That means you will traverse the tree for insertion "in layers". Queue should be your new friend here:-) (not the stack/recursion):
public void insert(int data) {
if (root == null) {
root = new Node(data);
return;
}
Queue<Node> nodesToProcess = new LinkedList<>();
nodesToProcess.add(root);
while (true) {
Node actualNode = nodesToProcess.poll();
// Left child has precedence over right one
if (actualNode.left == null) {
actualNode.left = new Node(data);
return;
}
if (actualNode.right == null) {
actualNode.right = new Node(data);
return;
}
// I have both children set, I will process them later if needed
nodesToProcess.add(actualNode.left);
nodesToProcess.add(actualNode.right);
}
}
Your method returns given node, but your method has to return inserted node which is node.right or node.left
Related
While I am working in the below code, I didn't understand how recursion is working, because insertLevelOrder() function after completing root.left functionality cursor is coming outside, but how root.right functionality invoking again.
As per the logic after incrementing 'i' value, in the middle again 'i' is becoming zero.
It is so much of confusing, please help me some one to understand, Thanks in advance.
// Java program to construct binary tree from
// given array in level order fashion
public class ConstructTree {
Node root;
// Tree Node
static class Node {
int data;
Node left, right;
Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
// Function to insert nodes in level order
public Node insertLevelOrder(int[] arr, Node root,
int i)
{
// Base case for recursion
if (i < arr.length) {
Node temp = new Node(arr[i]);
root = temp;
// insert left child
root.left = insertLevelOrder(arr, root.left,
2 * i + 1);
// insert right child
root.right = insertLevelOrder(arr, root.right,
2 * i + 2);
}
return root;
}
// Function to print tree nodes in InOrder fashion
public void inOrder(Node root)
{
if (root != null) {
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
}
}
// Driver program to test above function
public static void main(String args[])
{
ConstructTree t2 = new ConstructTree();
int arr[] = { 6, 6};
t2.root = t2.insertLevelOrder(arr, t2.root, 0);
t2.inOrder(t2.root);
}
}
Is it possible to write a binary search tree in C without pointers?
I have written using pointers as follows.
Working BST code in C using pointers
#include <stdio.h>
#include <malloc.h>
typedef struct node
{
int data;
struct node* left;
struct node* right;
}Node;
Node* root = NULL;
int insert(int);
int display(Node*);
int main(void)
{
int n = 0;
while(1)
{
printf("Enter data : ");
scanf("%d",&n);
if(n == -1)
break;
insert(n);
}
display(root);
return 0;
}
int insert(int data)
{
Node* node = malloc(sizeof(Node));
node->data = data;
node->left = NULL;
node->right = NULL;
Node* parent;
Node* trav;
if(root == NULL)
root = node;
else
{
trav = root;
while(trav != NULL)
{
parent = trav;
if(node->data < trav->data)
trav = trav->left;
else
trav = trav->right;
}
if(node->data < parent->data)
parent->left = node;
else
parent->right = node;
}
}
int display(Node* node)
{
if(node == NULL)
return 0;
display(node->left);
printf("%d ",node->data);
display(node->right);
}
Is is possible to write a BST without pointers, and using Nodes only. So, I want to access the left as node.left instead of node->left and so on. Even the members of the structure node should be like
typedef struct node
{
int data;
struct node left;
struct node right;
}Node;
and the Node members would be declared as
Node root; Node node;
and not as
Node* root; Node* node;
If it's not possible to write BST using the above structures, why is it so? Is it because, NULL is a pointer which has a value reserved for indicating that the pointer does not refer to a valid object. So, if we were using just a structure, we wouldn't know when to stop. So, I commented out the NULL lines in the above code, and made changes to access as structure members and not pointers. I was expecting it to atleast compile, although it would be an infinite loop at places. However, it gives me some compilation errors as well.
Tried BST code in C without using pointers, does not compile
#include <stdio.h>
#include <malloc.h>
typedef struct node
{
int data;
struct node left;
struct node right;
}Node;
//Node root = NULL;
Node root;
int insert(int);
int display(Node);
int rootformed = 0;
int main(void)
{
int n = 0;
while(1)
{
printf("Enter data : ");
scanf("%d",&n);
if(n == -1)
break;
insert(n);
}
display(root);
return 0;
}
int insert(int data)
{
Node node = malloc(sizeof(Node));
node.data = data;
node.left = NULL;
node.right = NULL;
Node parent;
Node trav;
if(rootformed == 0)
{
root = node;
rootformed = 1;
}
else
{
trav = root;
//while(trav != NULL)
while(1)
{
parent = trav;
if(node.data < trav.data)
trav = trav.left;
else
trav = trav.right;
}
if(node.data < parent.data)
parent.left = node;
else
parent.right = node;
}
}
int display(Node node)
{
//if(node == NULL)
//return 0;
display(node.left);
printf("%d ",node.data);
display(node.right);
}
However, I was going through how a binary search tree is implemented in Java, as follows. As seen below, members are accessed using the dot symbol. I'm curious to understand how it's done here.
If class is a structure, can I say that an object is a pointer to the
structure. The only difference being that in C, a pointer to a
structure uses the notation -> to access the internal members of the
structure, whereas, an object just uses . to access the internal
memebers of the structure(class)
Working BST code in java, which uses the . notation, got me thinking on how I can emulate this in C to use the . symbol and not ->
public class BinarySearchTree
{
public Node root;
public BinarySearchTree()
{
this.root = null;
}
public boolean find(int id)
{
Node current = root;
while(current!=null)
{
if(current.data == id)
{
return true;
}
else if(id < current.data)
{
current = current.left;
}
else
{
current = current.right;
}
}
return false;
}
public boolean delete(int id)
{
Node parent = root;
Node current = root;
boolean isLeftChild = false;
while(current.data != id)
{
parent = current;
if(id < current.data)
{
isLeftChild = true;
current = current.left;
}
else
{
isLeftChild = false;
current = current.right;
}
if(current ==null)
{
return false;
}
}
//if i am here that means we have found the node
//Case 1: if node to be deleted has no children
if(current.left==null && current.right==null)
{
if(current==root)
{
root = null;
}
if(isLeftChild ==true)
{
parent.left = null;
}
else
{
parent.right = null;
}
}
//Case 2 : if node to be deleted has only one child
else if(current.right==null)
{
if(current==root)
{
root = current.left;
}
else if(isLeftChild)
{
parent.left = current.left;
}
else
{
parent.right = current.left;
}
}
else if(current.left==null)
{
if(current==root)
{
root = current.right;
}
else if(isLeftChild)
{
parent.left = current.right;
}
else
{
parent.right = current.right;
}
}
else if(current.left!=null && current.right!=null)
{
//now we have found the minimum element in the right sub tree
Node successor = getSuccessor(current);
if(current==root)
{
root = successor;
}
else if(isLeftChild)
{
parent.left = successor;
}
else
{
parent.right = successor;
}
//successor.left = current.left;
}
return true;
}
public Node getSuccessor(Node deleteNode)
{
Node successsor =null;
Node successsorParent =null;
Node current = deleteNode.right;
while(current!=null)
{
successsorParent = successsor;
successsor = current;
current = current.left;
}
//check if successor has the right child, it cannot have left child for sure
//if it does have the right child, add it to the left of successorParent.
//successsorParent
if(successsor!=deleteNode.right)
{
successsorParent.left = successsor.right;
successsor.right = deleteNode.right;
}
if(successsor==deleteNode.right)
{
/* Then no more right tree */
}
successsor.left = deleteNode.left;
return successsor;
}
public void insert(int id)
{
Node newNode = new Node(id);
if(root==null)
{
root = newNode;
return;
}
Node current = root;
Node parent = null;
while(true)
{
parent = current;
if(id < current.data)
{
current = current.left;
if(current==null)
{
parent.left = newNode;
return;
}
}
else
{
current = current.right;
if(current==null)
{
parent.right = newNode;
return;
}
}
}
}
public void display(Node root)
{
if(root != null)
{
display(root.left);
System.out.print(" " + root.data);
display(root.right);
}
}
public static void main(String arg[])
{
BinarySearchTree b = new BinarySearchTree();
b.insert(3);b.insert(8);
b.insert(1);b.insert(4);b.insert(6);b.insert(2);b.insert(10);b.insert(9);
b.insert(20);b.insert(25);b.insert(15);b.insert(16);
System.out.println("Original Tree : ");
b.display(b.root);
System.out.println("");
System.out.println("Check whether Node with value 4 exists : " + b.find(4));
System.out.println("Delete Node with no children (2) : " + b.delete(2));
b.display(root);
System.out.println("\n Delete Node with one child (4) : " + b.delete(4));
b.display(root);
System.out.println("\n Delete Node with Two children (10) : " + b.delete(10));
b.display(root);
}
}
class Node
{
int data;
Node left;
Node right;
public Node(int data)
{
this.data = data;
left = null;
right = null;
}
}
In stead of pointers to memory objects, you can allocate a large array of Node objects and store indexes into this array in the left and right members.
Array entry 0 is the root node. You must keep track of the first unused array element to store a new Node. You can use calloc to allocate the array and realloc to enlarge the array.
You must keep track of deleted items: keep track of the first one and put in left the index of the next deleted item (kind of linked list). You can also keep track of the last deleted item to quickly append another deleted iem to the list.
You can implement binary search in an array, using array indexes instead of pointers. In C the array is just a language construct that automates pointer arithmetic and keeps it out of your code. If you malloc the entire array of structs and make the left and right members integers of some appropriate size, it can work.
But in structs created individually with malloc you can't do it without pointers because...
In C the structure is just memory allocated in a contiguous block. The . operator translates to a simple offset from the beginning of a block.
When you try to use the . operator to refer to .left or .right you are referring to a different struct that you created with a different malloc and it could be anywhere in heap memory. So the simple offset from the beginning of the current node is unknown.
So in C you need a pointer, to store the address of the left or right node.
In Java these are object references, essentially nicely wrapped and managed pointers. The JVM is managing allocation and tracking memory addresses, and this is mostly transparent to your code. You are, in effect, using pointers in the Java code, at run-time but your source code is written in terms of object references.
You could also implement binary search in C using a file or memory mapped file, using offsets into that file instead of C pointers. This is probably not what you intend in your question, but is/was often done in applications with large sorted data sets that need binary search.
I have been trying to write a program for creating a binary tree .I wish add nodes level by level .When i google the topic all i get is binary search tree .
here is the code
public class BinaryTree
{
public static void main(String[] args)
throws NullPointerException
{
Tree myTree = new Tree();
myTree.add(2,new Node(4));
myTree.add(4,new Node(5));
myTree.add(2,new Node(6));
//myTree.add(2,new Node(7));
}
}
class Node
{
int data;
boolean visited;
Node left,right;
Node(int data)
{
left=null;
right=null;
visited=false;
this.data=data;
}
}
class Tree
{
Node root;
int level,cLevel;
Tree()
{
root=null;
level=0;
cLevel=level-1;
}
protected void add(int data,Node node)
{
System.out.println("node.data k: "+node.data);
Node t;
if(root==null)
{
Node n=new Node(data);
root=n;
root.visited=true;
System.out.println("root visited"+root.data+""+root.visited);
level++;
cLevel++;
return;
}
while(root!=null)
{
}
}
}
I want to add new nodes level by level ,new level should not be created until a level isnt comleted ,all i get by googling is binary search tree .what should i do ,i have tried to use
depth first and breath first approach which didnt prrove helpfull .
You could achieve this by maintaining a queue of nodes which do not yet have two children. Every time you add a new node, stick it on the end of this queue, and also make it a child of the node at the front of this queue. Once the node at the front has two children, remove it from the queue. This way you'll build it up one level at a time, left to right, and only move on to the next level once the current one is finished.
You could also try "Limited Depth-first search"
A recursive implementation in Java using part of your code could be:
class Tree
{
Node root;
int level,cLevel;
Tree()
{
root=null;
level=0;
cLevel=level-1;
}
protected void add(int data)
{
System.out.println("data k: "+ data);
Node t;
if(root==null)
{
root=new Node(data);
level++;
} else {
cLevel = 0;
boolean added = add(data, root);
//Couldn't add to current level, add new level
if (!added){
level++;
cLevel = 0;
add(data, root);
}
}
}
private boolean add(int data, Node node)
{
cLevel++;
boolean added;
//Depth limited
if (cLevel<=level){
added = true;
//Try to add to current node
if (node.left == null)
node.left = new Node(data);
else if (node.right == null)
node.right = new Node(data);
else if (!add(data, node.left)) //Recursively trying to add to children
added = add(data, node.right);
} else {
added=false;
}
cLevel--;
return added;
}
}
Hope it helps.
Done with it.Thanks Animatinator .Although i have tested it with hardcode as i do not have time right now ,i have a paper early morning of Compiler Construction .
protected void add(int data,Tree mytree)
{
if(root==null)
{
root=new Node(data);
myList.addLast(root);
root.count++;
return;
}
Node node=mytree.myList.getFirst();
if(root!=null)
{
if(node.left==null)
{
node.count++;
node.left=new Node(data);
mytree.myList.add(node.left);
return;
}
else
{
node.count++;
node.right=new Node(data);
mytree.myList.add(node.right);
}
if(node.left!=null & node.right!=null)
{
mytree.myList.removeFirst();
}
}
}
I got an insert method and a search method, and I was thinking of a way to loop through the binary search tree and use a method like get nodes then search for it on the other binary search tree and if it comes true then I insert it that element, but the problem is I can't come up with a way to get the nodes based on index because its different than linkedList for example and can't think of a way to get the nodes to begin with; to sum up, I actually don't the proper way to start to solve that question.
public class BinarySearchTree extends BinaryTree {
//default constructor
//Postcondition: root = null;
public BinarySearchTree() {
super();
}
//copy constructor
public BinarySearchTree(BinarySearchTree otherTree) {
super(otherTree);
}
public class BinaryTree {
//Definition of the node
protected class BinaryTreeNode {
DataElement info;
BinaryTreeNode llink;
public DataElement getInfo() {
return info;
}
public BinaryTreeNode getLlink() {
return llink;
}
public BinaryTreeNode getRlink() {
return rlink;
}
BinaryTreeNode rlink;
}
protected BinaryTreeNode root;
//default constructor
//Postcondition: root = null;
public BinaryTree() {
root = null;
}
//copy constructor
public BinaryTree(BinaryTree otherTree) {
if (otherTree.root == null) //otherTree is empty
{
root = null;
} else {
root = copy(otherTree.root);
}
}
public BinaryTreeNode getRoot() {
return root;
}
public boolean search(DataElement searchItem) {
BinaryTreeNode current;
boolean found = false;
current = root;
while (current != null && !found) {
if (current.info.equals(searchItem)) {
found = true;
} else if (current.info.compareTo(searchItem) > 0) {
current = current.llink;
} else {
current = current.rlink;
}
}
return found;
}
public int countEven() {
return countEven(root);
}
public void insert(DataElement insertItem) {
BinaryTreeNode current;
BinaryTreeNode trailCurrent = null;
BinaryTreeNode newNode;
newNode = new BinaryTreeNode();
newNode.info = insertItem.getCopy();
newNode.llink = null;
newNode.rlink = null;
if (root == null) {
root = newNode;
} else {
current = root;
while (current != null) {
trailCurrent = current;
if (current.info.equals(insertItem)) {
System.out.println("The insert item is already in" + "the list -- duplicates are" + "not allowed.");
return;
} else if (current.info.compareTo(insertItem) > 0) {
current = current.llink;
} else {
current = current.rlink;
}
}
if (trailCurrent.info.compareTo(insertItem) > 0) {
trailCurrent.llink = newNode;
} else {
trailCurrent.rlink = newNode;
}
}
}
Traverse down to the left end of one tree, compare it with the root node of the other tree. If found equal, insert it into your third tree. If unequal, then check if it's less than or greater than the root of second tree. If less than, then traverse to the left child of the second tree and call your search method again, else, traverse to the right child of the second tree and call your search method again. Then repeat the whole process with the right node of the opposing starting node of first tree that you chose and call the search method again. Keep moving up the first tree as you repeat the process.
Here's a sample code(keeping in mind you have not provided any details about your trees whatsoever):
void search(Node node1, Node root2){
if(root2 == null)
return;
if(node1.data == root2.data){
//copy to your third tree
return;
}
else{
if(node1.data < root2.data){
root2 = root2.left;
search(node1, root2);
}
else{
root2 = root2.right;
search(node1, root2);
}
}
}
void common(Node root1, Node root2){
if(root1 != null){
common(root1.left, root2);
search(root1, root2);
common(root1.right, root2);
}
}
I'm assuming you need to modify the BinarySearchTree class, so the following is written with that assumption.
You can traverse the tree by first calling getRoot() which will return the root of the tree (a BinaryTreeNode) then access the nodes' left and right children by calling getLLink() and getRLink(), respectively. From each node you can get its value via getInfo that you can search for in the other tree (by calling the search() method on the second tree).
Note: as it is, you can only call methods on the nodes from within methods of BinarySearchTree as access to BinaryTreeNode is restricted to BinaryTree and classes deriving from it (for which BinarySearchTree qualifies)
This is what I have. I thought pre-order was the same and mixed it up with depth first!
import java.util.LinkedList;
import java.util.Queue;
public class Exercise25_1 {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree(new Integer[] {10, 5, 15, 12, 4, 8 });
System.out.print("\nInorder: ");
tree.inorder();
System.out.print("\nPreorder: ");
tree.preorder();
System.out.print("\nPostorder: ");
tree.postorder();
//call the breadth method to test it
System.out.print("\nBreadthFirst:");
tree.breadth();
}
}
class BinaryTree {
private TreeNode root;
/** Create a default binary tree */
public BinaryTree() {
}
/** Create a binary tree from an array of objects */
public BinaryTree(Object[] objects) {
for (int i = 0; i < objects.length; i++) {
insert(objects[i]);
}
}
/** Search element o in this binary tree */
public boolean search(Object o) {
return search(o, root);
}
public boolean search(Object o, TreeNode root) {
if (root == null) {
return false;
}
if (root.element.equals(o)) {
return true;
}
else {
return search(o, root.left) || search(o, root.right);
}
}
/** Return the number of nodes in this binary tree */
public int size() {
return size(root);
}
public int size(TreeNode root) {
if (root == null) {
return 0;
}
else {
return 1 + size(root.left) + size(root.right);
}
}
/** Return the depth of this binary tree. Depth is the
* number of the nodes in the longest path of the tree */
public int depth() {
return depth(root);
}
public int depth(TreeNode root) {
if (root == null) {
return 0;
}
else {
return 1 + Math.max(depth(root.left), depth(root.right));
}
}
/** Insert element o into the binary tree
* Return true if the element is inserted successfully */
public boolean insert(Object o) {
if (root == null) {
root = new TreeNode(o); // Create a new root
}
else {
// Locate the parent node
TreeNode parent = null;
TreeNode current = root;
while (current != null) {
if (((Comparable)o).compareTo(current.element) < 0) {
parent = current;
current = current.left;
}
else if (((Comparable)o).compareTo(current.element) > 0) {
parent = current;
current = current.right;
}
else {
return false; // Duplicate node not inserted
}
}
// Create the new node and attach it to the parent node
if (((Comparable)o).compareTo(parent.element) < 0) {
parent.left = new TreeNode(o);
}
else {
parent.right = new TreeNode(o);
}
}
return true; // Element inserted
}
public void breadth() {
breadth(root);
}
// Implement this method to produce a breadth first
// search traversal
public void breadth(TreeNode root){
if (root == null)
return;
System.out.print(root.element + " ");
breadth(root.left);
breadth(root.right);
}
/** Inorder traversal */
public void inorder() {
inorder(root);
}
/** Inorder traversal from a subtree */
private void inorder(TreeNode root) {
if (root == null) {
return;
}
inorder(root.left);
System.out.print(root.element + " ");
inorder(root.right);
}
/** Postorder traversal */
public void postorder() {
postorder(root);
}
/** Postorder traversal from a subtree */
private void postorder(TreeNode root) {
if (root == null) {
return;
}
postorder(root.left);
postorder(root.right);
System.out.print(root.element + " ");
}
/** Preorder traversal */
public void preorder() {
preorder(root);
}
/** Preorder traversal from a subtree */
private void preorder(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.element + " ");
preorder(root.left);
preorder(root.right);
}
/** Inner class tree node */
private class TreeNode {
Object element;
TreeNode left;
TreeNode right;
public TreeNode(Object o) {
element = o;
}
}
}
Breadth first search
Queue<TreeNode> queue = new LinkedList<BinaryTree.TreeNode>() ;
public void breadth(TreeNode root) {
if (root == null)
return;
queue.clear();
queue.add(root);
while(!queue.isEmpty()){
TreeNode node = queue.remove();
System.out.print(node.element + " ");
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
}
Breadth first is a queue, depth first is a stack.
For breadth first, add all children to the queue, then pull the head and do a breadth first search on it, using the same queue.
For depth first, add all children to the stack, then pop and do a depth first on that node, using the same stack.
It doesn't seem like you're asking for an implementation, so I'll try to explain the process.
Use a Queue. Add the root node to the Queue. Have a loop run until the queue is empty. Inside the loop dequeue the first element and print it out. Then add all its children to the back of the queue (usually going from left to right).
When the queue is empty every element should have been printed out.
Also, there is a good explanation of breadth first search on wikipedia: http://en.wikipedia.org/wiki/Breadth-first_search
public void breadthFirstSearch(Node root, Consumer<String> c) {
List<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node n = queue.remove(0);
c.accept(n.value);
if (n.left != null)
queue.add(n.left);
if (n.right != null)
queue.add(n.right);
}
}
And the Node:
public static class Node {
String value;
Node left;
Node right;
public Node(final String value, final Node left, final Node right) {
this.value = value;
this.left = left;
this.right = right;
}
}
//traverse
public void traverse()
{
if(node == null)
System.out.println("Empty tree");
else
{
Queue<Node> q= new LinkedList<Node>();
q.add(node);
while(q.peek() != null)
{
Node temp = q.remove();
System.out.println(temp.getData());
if(temp.left != null)
q.add(temp.left);
if(temp.right != null)
q.add(temp.right);
}
}
}
}
This code which you have written, is not producing correct BFS traversal:
(This is the code you claimed is BFS, but in fact this is DFS!)
// search traversal
public void breadth(TreeNode root){
if (root == null)
return;
System.out.print(root.element + " ");
breadth(root.left);
breadth(root.right);
}
For implementing the breadth first search, you should use a queue. You should push the children of a node to the queue (left then right) and then visit the node (print data). Then, yo should remove the node from the queue. You should continue this process till the queue becomes empty. You can see my implementation of the BFS here: https://github.com/m-vahidalizadeh/foundations/blob/master/src/algorithms/TreeTraverse.java
Use the following algorithm to traverse in breadth first search-
First add the root node into the queue with the put method.
Iterate while the queue is not empty.
Get the first node in the queue, and then print its value.
Add both left and right children into the queue (if the current
nodehas children).
Done. We will print the value of each node, level by level,by
poping/removing the element
Code is written below-
Queue<TreeNode> queue= new LinkedList<>();
private void breadthWiseTraversal(TreeNode root) {
if(root==null){
return;
}
TreeNode temp = root;
queue.clear();
((LinkedList<TreeNode>) queue).add(temp);
while(!queue.isEmpty()){
TreeNode ref= queue.remove();
System.out.print(ref.data+" ");
if(ref.left!=null) {
((LinkedList<TreeNode>) queue).add(ref.left);
}
if(ref.right!=null) {
((LinkedList<TreeNode>) queue).add(ref.right);
}
}
}
The following is a simple BFS implementation for BinaryTree with java 8 syntax.
void bfsTraverse(Node node, Queue<Node> tq) {
if (node == null) {
return;
}
System.out.print(" " + node.value);
Optional.ofNullable(node.left).ifPresent(tq::add);
Optional.ofNullable(node.right).ifPresent(tq::add);
bfsTraverse(tq.poll(), tq);
}
Then invoke this with root node and a Java Queue implementation
bfsTraverse(root, new LinkedList<>());
Even better if it is regular tree, could use following line instead as there is not only left and right nodes.
Optional.ofNullable(node.getChildern()).ifPresent(tq::addAll);
public static boolean BFS(ListNode n, int x){
if(n==null){
return false;
}
Queue<ListNode<Integer>> q = new Queue<ListNode<Integer>>();
ListNode<Integer> tmp = new ListNode<Integer>();
q.enqueue(n);
tmp = q.dequeue();
if(tmp.val == x){
return true;
}
while(tmp != null){
for(ListNode<Integer> child: n.getChildren()){
if(child.val == x){
return true;
}
q.enqueue(child);
}
tmp = q.dequeue();
}
return false;
}