I need to build a balanced binary search tree. So far my program inserts the numbers from 1 to 26, but my program does not build it into a balanced binary search tree. If anyone could look at my code and help me out it would be much appreciated.
public class TreeNode {
TreeNode leftTreeNode, rightTreeNode;// the nodes
int data;
//int size;
public TreeNode(){//Constructer
leftTreeNode = null;
rightTreeNode = null;
}
public TreeNode(int newData){//Constructer with new Data coming in for comparison
leftTreeNode = null;
rightTreeNode = null;
data = newData;
}
public TreeNode getLeft(){
return leftTreeNode;
}
public TreeNode getRight(){
return rightTreeNode;
}
public void setLeft(TreeNode leftTreeNode){
this.leftTreeNode = leftTreeNode;
}
public void setRight(TreeNode rightTreeNode){
this.rightTreeNode = rightTreeNode;
}
public int getData(){
return data;
}
// public boolean isEmpty(){//Checking to see if the the root is empty
// if(size == 0) return true;
// else return false;
public void print(){
System.out.println("Data is: " + getData());
}
}
// public void traverse (Node root){ // Each child of a tree is a root of its subtree.
// if (root.getLeft() != null){
// traverse (root.getLeft());
// }
// System.out.println(root.data);
// if (root.getRight() != null){
// traverse (root.getRight());
// }
//}
public class BinarySearchTree {
TreeNode root;
public BinarySearchTree(){
root = null;
}
public TreeNode getRoot(){
return root;
}
public void insert(int data) { //Insert method checking to see where to put the nodes
TreeNode node1 = new TreeNode(data);
if (root == null) {
root = node1;
}
else{
TreeNode parIns = root;//Parent
TreeNode insNode = root;//Insertion Node
while(insNode != null){
parIns = insNode;
if(data < insNode.getData()){//If the data is less than the data coming in place it on the left
insNode = insNode.getLeft();
}else{//Place it on the right
insNode = insNode.getRight();
}
}//Searching where to put the node
if(data < parIns.getData()){
parIns.setLeft(node1);
}else{
parIns.setRight(node1);
}
}
}
public void printInorder(TreeNode n){
if(n != null){
printInorder(n.getLeft());//L
n.print();//N
printInorder(n.getRight());//R
}
}
// public TreeNode balance(tree, int start, int end){
// if(start > end) return null;
// int mid = (start + end) /2;
// TreeNode node;
// TreeNode leftChild;
// TreeNode rightChild;
//
// if(node <= mid){
// leftChild = balance(arr[mid -1], start, end);/*Make the left child if the node coming in is
// less than the mid node */
//
//
// }else{
// rightChild = balance(arr[mid]+1, start, end);/*Make the rigth child if the node is
// greater than the mid node*/
//
// }
// return node;
// }
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
tree.insert(1);
tree.insert(2);
tree.insert(3);
tree.insert(4);
tree.insert(5);
tree.insert(6);
tree.insert(7);
tree.insert(8);
tree.insert(9);
tree.insert(10);
tree.insert(11);
tree.insert(12);
tree.insert(13);
tree.insert(14);
tree.insert(15);
tree.insert(16);
tree.insert(17);
tree.insert(18);
tree.insert(19);
tree.insert(20);
tree.insert(21);
tree.insert(22);
tree.insert(23);
tree.insert(24);
tree.insert(25);
tree.insert(26);
tree.printInorder(tree.getRoot());
}
}
//for(int i = 1; i <= 26; i++)
//tree.insert(i);
public void balance(TreeNode tree, int start, int end){
TreeNode tree1 = new TreeNode(data);
if(start <= end){
int mid = (start + end) /2;
//TreeNode node;
TreeNode leftChild;
TreeNode rightChild;
if(tree1.getData() <= mid){
leftChild = balance(tree1(mid -1), start, end);/*Make the left child if the node coming in is
less than the mid node */
}else{
rightChild = balance(tree1(mid+1), start, end);/*Make the rigth child if the node is
greater than the mid node*/
}
}
}
How can I fix the balance function to properly balance my tree?
Since your tree does not self-balance, whether or not it's balanced will depend on the order of insertion of the elements.
If you want your tree to be balanced regardless, you will need to take care of the balancing in your class. For example, take a look at the Red-Black Tree data structure.
public class BinarySearchTree {
TreeNode root;
public BinarySearchTree(){
root = new TreeNode();
}
public TreeNode getRoot(){
return root;
}
public void insert(int data) {
root = insert(root, data);
}//Insert method checking to see where to put the nodes
// public void insert(TreeNode node, int data){
// TreeNode node1 = new TreeNode(data);
// if (root == null) {
// root = node1;
// }
// else{
// TreeNode parIns = root;//Parent
// TreeNode insNode = root;//Insertion Node
//
// while(insNode != null){
// parIns = insNode;
//
// if(data < insNode.getData()){//If the data is less than the data coming in place it on the left
// insNode = insNode.getLeft();
// }else{//Place it on the right
// insNode = insNode.getRight();
// }
// }//Searching where to put the node
//
// if(data < parIns.getData()){
// parIns.setLeft(node1);
// }else{
// parIns.setRight(node1);
// }
//
// }
// }
private TreeNode insert(TreeNode node, int data) {
if(root.data == 0)
root.data = data;
else if (node==null) {
node = new TreeNode(data);
}
else {
if (data <= node.data) {
node.leftTreeNode = insert(node.leftTreeNode, data);
}
else {
node.rightTreeNode = insert(node.rightTreeNode, data);
}
}
return(node); // in any case, return the new pointer to the caller
}
public void printPreOrder(){
printPreOrder(root);
}
public void printPreOrder(TreeNode n){
if(n != null){
n.print();//N
printPreOrder(n.getLeft());//L
printPreOrder(n.getRight());//R
}
}
public TreeNode balance(int[] a, int start, int end){
TreeNode node = new TreeNode();
if(start <= end){
int mid = start + (end - start) /2;
node.data = a[mid];
if(root.data == 0)
root = node;
node.leftTreeNode = balance(a, start, mid -1);/*Make the left child if the node coming in is
less than the mid node */
node.rightTreeNode = balance(a, mid + 1, end);/*Make the rigth child if the node is
greater than the mid node*/
}
else{
return null;
}
return node;
}
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
//int[] a = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,21,22,23,24,25,26};
int[] a = new int[26];
for(int i = 0; i < 26; i++){
a[i] = i + 1;
}
for(int i = 1; i <= 26; i++)
tree.insert(i);
tree.printPreOrder();
BinarySearchTree tree2 = new BinarySearchTree();
tree2.balance(a, 0, 25);
System.out.println("Now I am going to balance my tree");
tree2.printPreOrder();
}
}
public class TreeNode {
TreeNode leftTreeNode, rightTreeNode;// the nodes
int data;
//int size;
public TreeNode(){//Constructer
leftTreeNode = null;
rightTreeNode = null;
data = 0;
}
public TreeNode(int newData){//Constructer with new Data coming in for comparison
leftTreeNode = null;
rightTreeNode = null;
data = newData;
}
public TreeNode getLeft(){
return leftTreeNode;
}
public TreeNode getRight(){
return rightTreeNode;
}
public void setLeft(TreeNode leftTreeNode){
this.leftTreeNode = leftTreeNode;
}
public void setRight(TreeNode rightTreeNode){
this.rightTreeNode = rightTreeNode;
}
public int getData(){
return data;
}
// public boolean isEmpty(){//Checking to see if the the root is empty
// if(size == 0) return true;
// else return false;
public void print(){
System.out.println("Data is: " + getData());
}
}
Related
hi im new to codings and i have to print my binary search tree in a 2d model but this codes only print the orders of number in order(left-root-right) such as when i insert 10, 9, 11, 8, it will print inorder (left root right) = 8,9,10,11. what method or codes should i add to create a 2d tree here. sorry idk how to properly put the codes here just look at it like it is only a one code only.
class binarySearchTree {
class Node {
int key;
Node left, right;
int data;
public Node(int data){
key = data;
left = right = null;
}
}
// BST root node
Node root;
// Constructor for BST =>initial empty tree
binarySearchTree(){
root = null;
}
//delete a node from BST
void deleteKey(int key) {
root = delete_Recursive(root, key);
}
//recursive delete function
Node delete_Recursive(Node root, int key) {
//tree is empty
if (root == null) return root;
//traverse the tree
if (key < root.key) //traverse left subtree
root.left = delete_Recursive(root.left, key);
else if (key > root.key) //traverse right subtree
root.right = delete_Recursive(root.right, key);
else {
// node contains only one child
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
// node has two children;
//get inorder successor (min value in the right subtree)
root.key = minValue(root.right);
// Delete the inorder successor
root.right = delete_Recursive(root.right, root.key);
}
return root;
}
int minValue(Node root) {
//initially minval = root
int minval = root.key;
//find minval
while (root.left != null) {
minval = root.left.key;
root = root.left;
}
return minval;
}
// insert a node in BST
void insert(int key) {
root = insert_Recursive(root, key);
}
//recursive insert function
Node insert_Recursive(Node root, int key) {
//tree is empty
if (root == null) {
root = new Node(key);
return root;
}
//traverse the tree
if (key < root.key) //insert in the left subtree
root.left = insert_Recursive(root.left, key);
else if (key > root.key) //insert in the right subtree
root.right = insert_Recursive(root.right, key);
// return pointer
return root;
}
void inorder() {
inorder_Recursive(root);
}
// recursively traverse the BST
void inorder_Recursive(Node root) {
if (root != null) {
inorder_Recursive(root.left);
System.out.print(root.key + " x ");
inorder_Recursive(root.right);
}
}
//PostOrder Traversal - Left:Right:rootNode (LRn)
void postOrder(Node node) {
if (node == null)
return;
// first traverse left subtree recursively
postOrder(node.left);
// then traverse right subtree recursively
postOrder(node.right);
// now process root node
System.out.print(node.key + " ");
}
// InOrder Traversal - Left:rootNode:Right (LnR)
void inOrder(Node node) {
if (node == null)
return;
//first traverse left subtree recursively
inOrder(node.left);
//then go for root node
System.out.print(node.key + " ");
//next traverse right subtree recursively
inOrder(node.right);
}
//PreOrder Traversal - rootNode:Left:Right (nLR)
void preOrder(Node node) {
if (node == null)
return;
//first print root node first
System.out.print(node.key + " ");
// then traverse left subtree recursively
preOrder(node.left);
// next traverse right subtree recursively
preOrder(node.right);
}
// Wrappers for recursive functions
void postOrder_traversal() {
postOrder(root); }
void inOrder_traversal() {
inOrder(root); }
void preOrder_traversal() {
preOrder(root); }
}
here i found this codes in stackoverflow, i want te output like this, i can use this but i dont know how can i make this as user input for the data and make it insert the integer into a tree not this manually inserted of the integer. thankyou very much to whoever put effort to understand my question and my situation as newbie.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BTreePrinterTest {
private static Node<Integer> test2() {
Node<Integer> root = new Node<Integer>(2);
Node<Integer> n11 = new Node<Integer>(3);
Node<Integer> n12 = new Node<Integer>(5);
Node<Integer> n21 = new Node<Integer>(2);
Node<Integer> n22 = new Node<Integer>(6);
Node<Integer> n23 = new Node<Integer>(9);
Node<Integer> n31 = new Node<Integer>(5);
root.left = n11;
root.right = n12;
n11.left = n21;
n11.right = n22;
n12.left = n23;
n12.right = n31;
return root;
}
public static void main(String[] args) {
BTreePrinter.printNode(test2());
}
}
class Node<T extends Comparable<?>> {
Node<T> left, right;
T data;
public Node(T data) {
this.data = data;
}
}
class BTreePrinter {
public static <T extends Comparable<?>> void printNode(Node<T> root) {
int maxLevel = BTreePrinter.maxLevel(root);
printNodeInternal(Collections.singletonList(root), 1, maxLevel);
}
private static <T extends Comparable<?>> void printNodeInternal(List<Node<T>> nodes, int level, int maxLevel) {
if (nodes.isEmpty() || BTreePrinter.isAllElementsNull(nodes))
return;
int floor = maxLevel - level;
int endgeLines = (int) Math.pow(2, (Math.max(floor - 1, 0)));
int firstSpaces = (int) Math.pow(2, (floor)) - 1;
int betweenSpaces = (int) Math.pow(2, (floor + 1)) - 1;
BTreePrinter.printWhitespaces(firstSpaces);
List<Node<T>> newNodes = new ArrayList<Node<T>>();
for (Node<T> node : nodes) {
if (node != null) {
System.out.print(node.data);
newNodes.add(node.left);
newNodes.add(node.right);
} else {
newNodes.add(null);
newNodes.add(null);
System.out.print(" ");
}
BTreePrinter.printWhitespaces(betweenSpaces);
}
System.out.println("");
for (int i = 1; i <= endgeLines; i++) {
for (int j = 0; j < nodes.size(); j++) {
BTreePrinter.printWhitespaces(firstSpaces - i);
if (nodes.get(j) == null) {
BTreePrinter.printWhitespaces(endgeLines + endgeLines + i + 1);
continue;
}
if (nodes.get(j).left != null)
System.out.print("/");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(i + i - 1);
if (nodes.get(j).right != null)
System.out.print("\\");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(endgeLines + endgeLines - i);
}
System.out.println("");
}
printNodeInternal(newNodes, level + 1, maxLevel);
}
private static void printWhitespaces(int count) {
for (int i = 0; i < count; i++)
System.out.print(" ");
}
private static <T extends Comparable<?>> int maxLevel(Node<T> node) {
if (node == null)
return 0;
return Math.max(BTreePrinter.maxLevel(node.left), BTreePrinter.maxLevel(node.right)) + 1;
}
private static <T> boolean isAllElementsNull(List<T> list) {
for (Object object : list) {
if (object != null)
return false;
}
return true;
}
}
btw im learning this by my own, i tried merging the two codes but it gives me error i cant fix it.
I should have not made the whole exercise for you, so please try to understand the code. Tell me if something is not clear for you.
public static void main(String[] args) throws IOException {
System.out.println("Write your input");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
binarySearchTree b = new binarySearchTree();
b.input(lines);
b.print();
}
These functions go to binarySearchTree.
protected void printRecursive(Node node, int depth) {
System.out.println("");
for(int i = 0; i<depth; i++) {
System.out.print(" ");
}
System.out.print(node.key);
if(node.left != null) {
printRecursive(node.left, depth + 1);
}
if(node.right != null) {
printRecursive(node.right, depth + 1);
}
}
public void input(String s) throws IOException {
String[] strs = s.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
insert(Integer.parseInt(strs[i]));
}
}
Also i used this answer in my code.
I need to print all the nodes that are N level above all Leaf Nodes. I tried below approach, but now I am stuck and unable to proceed. Please help. I need to code only using Java 7 and no other versions.
For example, I have this path 1 --> 2 --> 3 --> 4, so in this case assuming 4 is my leaf node, node 3 is 1 level above 4 and node 2 is 2 levels above leaf node 4 and node 1 is 3 levels above leaf node 4.
Note: Please use only Java 7.
public class NNodeBeforeLeaf {
static Node root;
static class Node {
int data;
Node left, right;
Node(int data){
this.data = data;
left=right=null;
}
}
public static boolean isLeaf(Node n){
if(n.right == null && n.left == null)
return true;
return false;
}
public static void main(String[] args) {
int level = 2; // level N
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(8);
print(root, 0, level);
}
public static void print(Node n, int currLevel, int level){
if(n == null){
return;
}
if(!isLeaf(n)){
print(n.left, currLevel + 1, level);
print(n.right, currLevel + 1, level);
}
printNode(n, currLevel, level);
}
public static void printNode(Node n, int currLevel, int level){}
}
You have a miss in your structure to do this a Node know its child but not is parent so you need to build a structure that will give you this link : here is my proposition : i build a map that give me the parent associate to a node with method buildParentMap this function already list all the leaf in one pass to avoid a double iteration on your tree then i use this map to go up as many time as asked on each leaf i list just before here is a snippet
be carefull this code work but there is no security if your are trying to upper that root or if the same node is present in too child (but 2 Node with the same data wont be a problem)
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
public class NNodeBeforeLeaf {
static Node root;
static class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
#Override
public String toString() {
return "Node : " + data;
}
}
public static boolean isLeaf(Node n) {
if (n.right == null && n.left == null)
return true;
return false;
}
public static void main(String[] args) {
int level = 2; // level N
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(8);
print(root, 0, level);
int levelToUp = 1;
HashSet<Node> result = getUpper(levelToUp, root);
System.out.println(Arrays.toString(result.toArray()));
}
private static HashSet<Node> getUpper(int levelToUp, Node node) {
HashMap<Node, Node> parenttMap = new HashMap<Node, Node>();
LinkedList<Node> leafs = new LinkedList<Node>();
buildParentMap(node, parenttMap, leafs);
HashSet<Node> result = new HashSet<>();
for (Node leaf : leafs) {
result.add(getUpperLevel(leaf, levelToUp, parenttMap));
}
return result;
}
private static Node getUpperLevel(Node leaf, int i, HashMap<Node, Node> parenttMap) {
Node tmp = leaf;
while (i > 0) {
i--;
tmp = parenttMap.get(tmp);
}
return tmp;
}
private static void buildParentMap(Node root2, HashMap<Node, Node> hashMap, LinkedList<Node> leaf) {
if (root2 == null) {
return;
} else if (isLeaf(root2)) {
leaf.add(root2);
} else {
hashMap.put(root2.left, root2);
buildParentMap(root2.left, hashMap, leaf);
hashMap.put(root2.right, root2);
buildParentMap(root2.right, hashMap, leaf);
}
}
public static void print(Node n, int currLevel, int level) {
if (n == null) {
return;
}
printNode(n, currLevel, level);
if (!isLeaf(n)) {
print(n.left, currLevel + 1, level);
print(n.right, currLevel + 1, level);
}
}
public static void printNode(Node n, int currLevel, int level) {
String output = "";
for (int i = 0; i < currLevel; i++) {
output += "\t";
}
System.out.println(output + n);
}
}
PLEASE READ MY COMMENT FIRST
Since the nodes in your program store data only for the nodes below them, I couldn't really find a way of actually going up the tree ':), but I could think of this work around, basically what you can do is, each time you need to go up by n levels you can traverse down from the root to (curLevel - n) here is a sample program that does this (it prints all the nodes at a level which is n above the current level, i hope this is what you meant):
class tree{
static class Node{
int data;
Node left;
Node right;
Node(int data){
this.data = data;
left = null;
right = null;
}
}
static Node root;
public static boolean isLeaf(Node n){
if(n.left == null && n.right == null)
return true;
return false;
}
public static void goDownTillLevel(Node n, int level){
int l = level;
if(n != null){
if(level == 0) {
System.out.println(n.data);
}
else{
if(!isLeaf(n)){
goDownTillLevel(n.left, --level);
level = l; //since by the time the above function calls finished, level had been reduced to 0
goDownTillLevel(n.right, --level);
}
}
}
}
public static void nLevelsAbove(Node n, int curLevel, int level){
goDownTillLevel(root, (curLevel - level - 1));
}
public static void main(String args[]){
int curLevel = 0;
root = new Node(1);
curLevel++;
root.left = new Node(2);
root.right = new Node(2);
curLevel++;
root.left.left = new Node(3);
root.left.right = new Node(3);
root.right.left = new Node(3);
Node n = new Node(3);
root.right.right = n;
curLevel++;
nLevelsAbove(n, curLevel, 1);
}
}
Though I'd like to add that if going up is one of your concerns, don't use this node structure, instead add another variable to the node, a reference to the node right above it, that way this could be made much easier and shorter.
The output of the above code is:
2
2
I think that the implementation of public static boolean isLeaf(Node n) is wrong, it should check only if right is null otherwise it is not a node, either a leaf
To get the current level of node, you can try with this code
int level = 0;
while(node.right != null) {
level++;
node = node.right;
}
System.out.println("current level node: " + level);
Your structure is not able to determine the height of the current node, except when traversing from bottom to top. In order to achieve this, you have to traverse to the leafs first.
Each recursion (bottom up now) should then return it's heights. As youre not stating if your tree is a full binary tree, a node can have multiple heights depending on his children. If the heights match the desired height, the node can be printed.
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class NNodeBeforeLeaf {
static Node root;
static class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
}
public static boolean isLeaf(Node n) {
return n.right == null && n.left == null;
}
public static void main(String[] args) {
int level = 2; // level N
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(8);
print(root, level);
}
public static void print(Node n, int level) {
traversAndPrint(n, level);
}
private static Set<Integer> traversAndPrint(Node n, int levelToPrint) {
if (isLeaf(n)) return Collections.singleton(0); // We are a leaf, so we have height 0
final Set<Integer> childrenHeights = new HashSet<>();
// are no leaf, so we have to get the heights of our children
if (n.right != null) childrenHeights.addAll(traversAndPrint(n.right, levelToPrint));
if (n.left != null) childrenHeights.addAll(traversAndPrint(n.left, levelToPrint));
assert !childrenHeights.isEmpty();
// And increase these heights
final Set<Integer> selfHeights = new HashSet<>();
for (Integer childrenHeigth : childrenHeights) {
final int selfHeight = childrenHeigth + 1;
selfHeights.add(selfHeight);
}
// If we have the desired height, print
if (selfHeights.contains(levelToPrint)) printNode(n);
return selfHeights; // return our heights
}
public static void printNode(Node n) {
// Do whatever you want
System.out.println(n.data);
}
}
I found another approach. I put all nodes in a list. For each level up I remove the leaf nodes in that list. A leaf node in the list is defined as a node with left=null and right=null or if they are not null left and right should not be in the list. After the level ups I print the now leaf nodes in the list.
public class NNodeBeforeLeaf {
static Node root;
static class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
}
public static boolean isLeaf(Node n) {
if ((n.right == null) && (n.left == null)) {
return true;
}
return false;
}
public static void main(String[] args) {
int level = 2; // level N
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(8);
printNodes(getNodesNLevelAboveLeafs(root, level));
}
public static void printNodes(List<Node> nodes) {
for (Node n : nodes) {
System.out.println(n.data);
}
}
public static List<Node> getNodesNLevelAboveLeafs(Node root, int level) {
List<Node> allNodes = listAllNodes(root);
for (int i = 0; i < level; i++) {
allNodes.removeAll(getLeafNodes(allNodes));
}
return getLeafNodes(allNodes);
}
private static List<Node> getLeafNodes(List<Node> allNodes) {
List<Node> leafs = new ArrayList<>();
for (Node n : allNodes) {
if (((n.left == null) || !allNodes.contains(n.left))
&& ((n.right == null) || !allNodes.contains(n.right))) {
leafs.add(n);
}
}
return leafs;
}
private static List<Node> listAllNodes(Node node) {
List<Node> nodes = new ArrayList<>();
nodes.add(node);
if (node.left != null) {
nodes.addAll(listAllNodes(node.left));
}
if (node.right != null) {
nodes.addAll(listAllNodes(node.right));
}
return nodes;
}
}
I am supposed to return the oldest element in a priority min queue along with said element. I have to use nodes, arrays are optional. This is what I got so far but I have an null pointer error on line 20 and i don't know how to fix it. Please help
public class MinHeap {
public static int timeStamp = 0;
public static int ts = 0;
public static int maxTime = 0;
public static Node root;
public MinHeap(){
this.root = null;
}
public static void insert(int id, int ts){
timeStamp++;
Node newNode = new Node(id);
if(root==null){
root = newNode;
}
Node current = root;
Node parent = null;
while(true){
parent = current;
if(id < current.data){
current = current.left;
if(current==null){
parent.left = newNode;
}
}else{
current = current.right;
if(current==null){
parent.right = newNode;
}
}
}
}
public static Node delete(int x, Node n){
timeStamp++;
if(n==null)
return n;
if(x == n.data){
if(n.left == null && n.right == null){
return null;
}else if(n.left == null){
n.right = delete(x, n.right);
return n;
}else if(n.right == null){
n.left = delete(x, n.left);
return n;
}else{
Node tempNode = findMin(n.right);
n.right = delete(tempNode.data, n.right);
n.data = tempNode.data;
return n;
}
}
if(x < n.data){
n.left = delete(x, n.left);
return n;
}else{
n.right = delete(x, n.right);
return n;
}
}
public static void display(Node root){
if(root!=null){
display(root.left);
System.out.print(" " + root.data);
display(root.right);
}
}
public static Node findMin(Node n){
if(n == null){
return null;
}
if(n.left == null){
return n;
}
return findMin(n.left);
}
public static int maxAge(){
int currentAge = 0;
currentAge = timeStamp - ts;
if(currentAge > maxTime)
maxTime = currentAge;
return maxTime;
}
public static void main(String [] arg){
MinHeap min = new MinHeap();
min.insert(1, ts = 0);
min.insert(2, ts = 1);
min.insert(3, ts = 2);
min.insert(4, ts = 4);
min.delete(1, root);
min.delete(2, root);
min.delete(3, root);
min.delete(4, root);
min.maxAge();
}
}
class Node{
int data;
Node left;
Node right;
public Node(int data){
this.data = data;
left = null;
right = null;
}
}
Your insert is broken. You forgot to break after finding the insert point, and you're not checking for the case where the key is already in the tree.
while (true) {
parent = current;
if (id < current.data) {
current = current.left;
if (current == null) {
parent.left = newNode;
// Break after insert
break;
}
} else if (id > current.data) {
current = current.right;
if (current == null) {
parent.right = newNode;
// Break after insert
break;
}
} else {
// Key exists.
break;
}
}
I am trying to write a method that returns the depth of a target int in a binary search tree. Right now it works for some smaller trees, but not always. Does anyone see where I may be going wrong?
static int count=1;
public static int findDepth(TreeNode<Integer> root, int target)
// pre: 0 or more elements in the tree, integer to search for
// post: return depth of target if found, -1 otherwise
{
count++;
if (root!=null)
{
if (root.getValue()<target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
else
{findDepth(root.getLeft(), target);
count--;
findDepth(root.getRight(), target);
}
}
else if (root.getValue()>target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
else
{findDepth(root.getLeft(), target);
count--;
findDepth(root.getRight(), target);
}
}
else if (root.getValue()==target)
return 1;
else
return -1;
}
return count;
}
There's a few things wrong.
It will never get into this case:
if (root.getValue()<target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
Also it will never get into this case:
else if (root.getValue()>target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
The biggest issue is that you're keeping a global static count, and recursively going through both left and right paths.
First of all, for a BST, there is no need to go both left and right.
Second, it's better to pass the count through a parameter rather than keeping a global.
Rather than fix your code, I'll post this working example for you to use as a reference:
public class Main
{
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.add(20);
tree.add(10);
tree.add(30);
tree.add(15);
tree.add(25);
tree.add(5);
tree.add(35);
tree.add(1);
tree.add(6);
tree.add(14);
tree.add(16);
tree.add(24);
tree.add(26);
tree.add(34);
tree.add(36);
int level = tree.getLevel(6);
System.out.println(level);
}
}
public class TreeNode
{
int data;
TreeNode left;
TreeNode right;
public TreeNode(int d){
data = d;
left = null;
right = null;
}
}
public class BinaryTree
{
TreeNode root;
public BinaryTree(){
root = null;
}
public int getLevel(int val) {
if (root == null) return 0;
return getLevelHelper(root, val, 0);
}
public int getLevelHelper(TreeNode node, int val, int level){
int retVal = -1;
if (node.data == val){
return level;
}
if (val < node.data && node.left != null){
retVal = getLevelHelper(node.left, val, level + 1);
}
else if (val > node.data && node.right != null){
retVal = getLevelHelper(node.right, val, level + 1);
}
return retVal;
}
public boolean add(int newData){
if (root == null){
root = new TreeNode(newData);
return true;
}
else{
TreeNode curr = root;
while (true){
if (curr.data == newData){
return false;
}
else if (curr.data > newData){
if (curr.left == null){
curr.left = new TreeNode(newData);
return true;
}
else{
curr = curr.left;
}
}
else{
if (curr.right == null){
curr.right = new TreeNode(newData);
return true;
}
else{
curr = curr.right;
}
}
}
}
}
}
In this specific instance, it takes into account two occasions. One where I'm trying to place a node in the beginning of the Linked List and one where I'm trying to place it in the middle or at the end. Here is my Node Class. If you look at my INSERT method, the part that is not working is:
Node newNode = new Node();
newNode.setExponent(element);
class Node {
private int coefficient;
private int exponent;
private Node link;
// Constructor: Node()
Node(int c, int e) {
// Sets coefficient to c, exponent to e, and link to null
coefficient = c;
exponent = e;
link = null;
}
// Inspectors: getCoefficient(), getExponent(), getLink()
public int getCoefficient() {
// Returns coefficient
return coefficient;
}
public int getExponent() {
// Returns exponent
return exponent;
}
public Node getLink() {
// Returns link
return link;
}
// Modifiers: setCoefficient(), setExponent(), setLink()
public void setCoefficient(int c) {
// Sets coefficient to c
coefficient = c;
}
public void setExponent(int e) {
// Sets exponent to e
exponent = e;
}
public void setLink(Node n) {
// Sets link to n
link = n;
}
}// Ends Node Class
Here is where I'm trying to insert to my Linked List along with some other methods in the class that should help give you an idea of how my code looks.
class List {
private Node head; // Points to first element of the list
private int count; // number of elements in the list
// Constructor:
List() {
// Sets head to null and count to zero
head = null;
count = 0;
}
// Inspectors:
// Returns the number of elements in the list
public int size() {
return count;
}
// Modifiers:
// Inserts element at index in the list. Returns true if successful
public boolean insert(int index, Node element) {
if (index < 0 || index > count)return false;
if (index == 0) {
Node newNode = new Node();
newNode.setExponent(element);
count++;
newNode.setLink(head);
head = newNode;
return true;
}
Node walker = head;
for (int i = 1; i < (index - 1); i++)
walker = walker.getLink();
Node newNode = new Node();
newNode.setExponent(element);
newNode.setLink(walker.getLink());
walker.setLink(newNode);
count++;
return true;
}
Try this:
Assumption: You are trying to insert a Node element into the index of LinkedList
Your insert method with modification.
public boolean insert(int index, Node element) {
//if (index < 0 || index > count)
if (index < 0 || index > count + 1) return false;
if(head == null) {
head = element;
return true;
}
if (index == 0) {
//Node newNode = new Node();
//newNode.setExponent(element);
count++;
element.setLink(head);
//newNode.setLink(head);
head = element;
//head = newNode;
return true;
}
Node walker = head;
//for (int i = 0; i < (index - 1); i++)
for (int i = 1; i < index; i++) {
walker = walker.getLink();
}
//Node newNode = new Node();
//newNode.setExponent(element);
element.setLink(walker.getLink());
//newNode.setLink(walker.getLink());
//walker.setLink(newNode);
walker.setLink(element);
count++;
return true;
}
Sample Test Case:
print method:
void print() {
Node travel = head;
while(travel!= null) {
System.out.println(travel.getExponent() + " " + travel.getCoefficient());
travel = travel.getLink();
}
}
Main method:
public static void main(String args[]) {
Node n1 = new Node(1,2);
List l = new List();
l.insert(0,n1);
Node n2 = new Node(3,2);
l.insert(1,n2);
Node n3 = new Node(4,5);
l.insert(0,n3);
l.print();
}