package BinaryTree;
public class BinaryTreeNode {
public int data;
public BinaryTreeNode left;
public BinaryTreeNode right;
public BinaryTreeNode(int data) {
this.data = data;
left = null;
right = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public BinaryTreeNode getLeft() {
return left;
}
public void setLeft(BinaryTreeNode left) {
this.left = left;
}
public BinaryTreeNode getRight() {
return right;
}
public void setRight(BinaryTreeNode right) {
this.right = right;
}
public String toString(BinaryTreeNode root) {
String result = "[";
while(root.getLeft()!=null){
result = result + root.getData();
}
while(root.getRight()!=null){
result = result + root.getData();
}
result+="]";
return result;
}
/* public String toString() {
String result = "";
result = result+"--" + data + "Left Child:-" + left + "Right Child:-" + right + "\n";
return result;
}*/
}
public class BinaryTreeNode {
public int data;
public BinaryTreeNode left;
public BinaryTreeNode right;
public BinaryTreeNode(int data) {
this.data = data;
left = null;
right = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public BinaryTreeNode getLeft() {
return left;
}
public void setLeft(BinaryTreeNode left) {
this.left = left;
}
public BinaryTreeNode getRight() {
return right;
}
public void setRight(BinaryTreeNode right) {
this.right = right;
}
public String toString(BinaryTreeNode root) {
String result = "[";
while(root.getLeft()!=null){
result = result + root.getData();
}
while(root.getRight()!=null){
result = result + root.getData();
}
result+="]";
return result;
}
/* public String toString() {
String result = "";
result = result+"--" + data + "Left Child:-" + left + "Right Child:-" + right + "\n";
return result;
}*/
}
package BinaryTree;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class testBinaryTree {
int diameter = 0;
int left, right;
public BinaryTreeNode insertBinartTree(BinaryTreeNode root, int data) {
if (root == null) {
return null;
}
Queue<BinaryTreeNode> q = new LinkedList<BinaryTreeNode>();
q.offer(root);
while (!q.isEmpty()) {
BinaryTreeNode tmp = q.poll();
/**
* here both if condition working parallel.
*/
if (tmp != null) {
if (tmp.getLeft() != null)
q.offer(tmp.getLeft());
else {
tmp.left = new BinaryTreeNode(data);
return root;
}
}
if (tmp.getRight() != null) {
q.offer(tmp.right);
} else {
tmp.right = new BinaryTreeNode(data);
return root;
}
}
return root;
}
}