Question : Write the code to Create the Binary Tree from given elements?
Ans : Example : 1,2,3,4,5,7
Binary Tree: 1
/ \
2 3
/ \
4 5
/
7
Here is the Code :
public class BinaryTreeConstruction {
public static void main(String[] args) {
/* Create root of the Binary Tree */
Node node = new Node(1);
if(root == null){
root = node;
}
int[] values = {2,3,4,5,7};
for(int val: values)
{
constructBinaryTree(node,val);
}
}
/* Construct Binary Tree */
private static void constructBinaryTree(Node node,int val)
Ans : Example : 1,2,3,4,5,7
Binary Tree: 1
/ \
2 3
/ \
4 5
/
7
Here is the Code :
public class BinaryTreeConstruction {
public static void main(String[] args) {
/* Create root of the Binary Tree */
Node node = new Node(1);
if(root == null){
root = node;
}
int[] values = {2,3,4,5,7};
for(int val: values)
{
constructBinaryTree(node,val);
}
}
/* Construct Binary Tree */
private static void constructBinaryTree(Node node,int val)
{
Node newNode = new Node(val);
if(node.left == null)
{
node.left = newNode;
}
else if(node.right == null)
{
node.right = newNode;
}
else if(node.left != null)
{
while(node.left != null && node.right != null)
{
node = node.left;
} if(node.left == null)
{
node.left = newNode;
}else if(node.right == null)
{
node.right = newNode;
}
}
}
}/* Class Close */
Class Node :
public class Node {
int val;
Node left,right;
Node(int value){
left = right = null;
this.val = value;
}
}
Class Node :
public class Node {
int val;
Node left,right;
Node(int value){
left = right = null;
this.val = value;
}
}
No comments:
Post a Comment