The point of this project is to get an array from the user and use it to create a tree using nodes. The next step is to call a method to check if it represents a Binary Tree. I've been working on this for hours and can't seem to find the correct method to check.
Here is my code so far. I have done everything but the isBinaryTree() method to check if it is a Binary Tree.
import java.util.Scanner;
public class TestBinaryTree
{
Node root;
public void addNode(int key)
{
Node newNode = new Node(key);
if(root == null)
{
root = newNode;
}
else
{
Node focusNode = root;
Node parent;
while(true)
{
parent = focusNode;
if(key < focusNode.key)
{
focusNode = focusNode.leftChild;
if(focusNode == null)
{
parent.leftChild = newNode;
return;
}
}
else
{
focusNode = focusNode.rightChild;
if(focusNode == null)
{
parent.rightChild = newNode;
return;
}
}
}
}
}
/*public static boolean isBinaryTree(int rt, int lft, int rght)
{
}*/
public static void main(String[] args)
{
int Nroot, Nleft, Nright;
Scanner input = new Scanner(System.in);
TestBinaryTree theTree = new TestBinaryTree();
System.out.println("How many numbers are in the array: ");
int num = input.nextInt();
int arr[]=new int[num];
System.out.println("Enter the numbers: ");
for(int i=0;i<num;i++)
{
arr[i] = input.nextInt();
theTree.addNode(arr[i]);
}
}
}
class Node
{
int key;
Node leftChild;
Node rightChild;
Node(int key)
{
this.key = key;
}
public String toString()
{
return "Node: " + key;
}
}
Related
I'm new to Java and programming in general. The code works, mostly. It can do everything except for when I input the following:
Sequence: d, e, f, a, b, c, g, h, i, j.
Search for: b or c
I can't seem to find any issue with the code but have narrowed it down to the insertNode module/class, it seems like when users key in a, b, c after d, e, f, only node a register on the left side.
import java.util.Arrays;
import java.util.Scanner;
import java.lang.reflect.Method;
public class BinarySearchTreeTestStackOverflow {
class Node {
String stringData;
Node leftChild;
Node rightChild;
Node(String stringData) {
this.stringData = stringData;
leftChild = rightChild = null;
}
}
//root node for the binary tree
Node root;
//Constructor method
public BinarySearchTreeTestStackOverflow() {
root = null;
}
//Insert method for new values in the tree
public void insert(String key) {
root = insertNode(root, key);
}
//Insert recursive call for inserting from the root, in the right place
public Node insertNode(Node node, String key) {
if (node == null) {
node = new Node(key);
return node;
}
if (key.compareTo(node.stringData) < 0) {
node.leftChild = insertNode(node.leftChild, key);
} else if (key.compareTo(root.stringData) > 0) {
node.rightChild = insertNode(node.rightChild, key);
}
return node;
}
//Find method asking for the node to find
public Node find(String key) { //takes user input and turns it into a node
Node node = findNode(root, key);
System.out.println("print key to find: " + key);
return node;
}
//Find recursive method using the root node.
public Node findNode(Node node, String key) {
if (key.compareTo(node.stringData) == 0) {
return node;
}
//check up on findNodeMethod
if (key.compareTo(node.stringData) <= 0) {
if (node.leftChild == null) {
return null;
} else {
return findNode(node.leftChild, key);
}
} else if (key.compareTo(node.stringData) > 0) {
if (node.rightChild == null) {
return null;
} else {
System.out.println("went right"); //toDelete
return findNode(node.rightChild, key);
}
}
return null;
}
public static void main(String[] args) {
BinarySearchTreeTestStackOverflow binaryTree = new BinarySearchTreeTestStackOverflow();
Scanner scanner = new Scanner(System.in);
for (int i = 1; i <= 10; i++) {
System.out.print("Enter string " + i + " for the tree: ");
binaryTree.insert(scanner.nextLine());
}
System.out.print("Enter the value to be searched: ");
String key = scanner.nextLine(); //correct, verified using - System.out.println("key to be searched: "+ key);
Node node = binaryTree.find(key);
if (node == null) {
System.out.println("The string does not exist");
} else {
System.out.println("Node " + node.stringData + " was found");
}
}
}
The issue is inside insertNode(). Instead of comparing with root:
else if (key.compareTo(root.stringData) > 0) {
node.rightChild = insertNode(node.rightChild, key);
}
you should compare with node:
else if (key.compareTo(node.stringData) > 0) {
node.rightChild = insertNode(node.rightChild, key);
}
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 am currently in an intro data structures class and am really struggling with one of our problems about Binary Search Trees. This is the first time I have implemented this data structure and am doing my best to learn it.
Problem:
The program is supposed to create and search a BST of name and occurrence data, based upon the census data of babies born that year. We are given this data in a txt file.
I am having a lot of difficulty figuring out why it is not working. I am really just looking for someone to lead me in the right direction from here and give me some good feedback on what I already have because I feel really lost! My current work is below. I am implementing this in java. Thanks in advance!
public class Node {
String name;
int data;
Node leftChild;
Node rightChild;
public Node (String n, int d) {
name = n;
data = d;
}
public class BinarySearchTree` {
public static Node root;
public void addNode(String name, int data) {
Node newNode = new Node(name, data);
if (root == null) {
root = newNode;
} else {
Node focusNode = root;
Node parent;
while(true) {
parent = focusNode;
if (name.compareTo(focusNode.name) < 0) {
focusNode = focusNode.leftChild;
if (focusNode == null) {
parent.leftChild = newNode;
return;
} else {
focusNode = focusNode.rightChild;
if (focusNode == null) {
parent.rightChild = newNode;
return;
}
}
}
}
}
}
public Node searchName(String name) {
Node focusNode = root;
while (!focusNode.name.equals(name)) {
if (name.compareTo(focusNode.name) < 0) {
focusNode = focusNode.leftChild;
} else {
focusNode = focusNode.rightChild;
}
if (focusNode == null) {
return null;
}
}
return focusNode;
}
public static void main(String[] args) throws Exception {
BinarySearchTree tree = new BinarySearchTree();
FileReader file = new FileReader("/Users/mattspahr/Desktop/test.txt");
BufferedReader reader = new BufferedReader(file);
String str = null,
name = null,
num = null;
int data;
while(reader.readLine() != null) {
str = reader.readLine();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= '0' || c <= '9') {
name = str.substring(0, i);
}
num = str.replaceAll("[^0-9]" , "");
}
data = Integer.parseInt(num);
tree.addNode(name,data);
Node n = tree.searchName("Buffy ");
System.out.println(n);
}
}
}
I couldn't figure out how to store the number of times a recursive method calls itself. If any one could point me in the right direction I would greatly appreciate it! Below is my code in it i have a comment on where I think I am going wrong.
package module8_auriemma_assignment;
import java.util.*;
public class fibonacciTree{
Node root;
public void addNode(int key, int num) {
Node newNode = new Node(key, num);
if (root == null) {
root = newNode;
}
else {
Node focusNode = root;
Node parent;
while (true) {
parent = focusNode;
if (key < focusNode.key) {
focusNode = focusNode.leftChild;
if (focusNode == null) {
parent.leftChild = newNode;
return;
}
}
else
{
focusNode = focusNode.rightChild;
if (focusNode == null) {
// then place the new node on the right of it
parent.rightChild = newNode;
return; // All Done
}
}
}
}
}
public static void main(String[] args) {
fibonacciTree theTree = new fibonacciTree();
Scanner input = new Scanner (System.in);
System.out.println("Please enter an index");
System.out.println("I will compute your index's Fibonacci numbers.");
System.out.println("I will compute numbers that do not exceed a billion");
int number;
int key;
key = 0;
for(number = input.nextInt(); number < 1000000; number++){
System.out.println(fibonacci(number));
theTree.addNode(key, number);
/*
I am not sure if I should be adding a new node everytime the
loop happens in the main class OR if I should be having it store
a node inside of the fibonacci method itself
*/
number++;
key++;
}
}
public static long fibonacci(int i)
{
if (i == 0) return 0;
if (i <= 2) return 1;
long fibTerm = fibonacci(i - 1) + fibonacci(i - 2);
if(fibTerm > 1000000000){
System.out.println("Number too large");
System.exit(0);
}
else{
return fibTerm;
}
return fibTerm;
}
}
.
package module8_auriemma_assignment;
class Node {
int key;
int num;
Node leftChild;
Node rightChild;
Node(int key, int num) {
this.key = key;
this.num = num;
}
#Override
public String toString() {
return num + " has the key " + key;
}
}
fibonacci(int i) keeps calling itself until it is reduced to a series of 1+1+1+1+1+1+1+1+1+1+1+...
The solution is also the number of times the method is called. If you want to know how many times it was called, look at the return value.
folks, I've implemented the code for counting the total number of Nodes in a binary tree and the method looks like the following:
public int countNodes(Node root){
int count = 0;
if(root == null){
System.out.println("The tree is empty!");
return -1;
}
else{
count = 1;
Node current = root;
if(current.leftChild != null){
count += countNodes(current.leftChild);
}
else if(current.rightChild != null){
count += countNodes(current.rightChild);
}
}
System.out.print("The total number of nodes in the tree is ");
return count;
}
The parameter of the method contains Node root but my question is when I try to run the method from the main class then what should I pass as a parameter??
what should I add inside the parameters here?:
int countNodes = tree1.countNodes("?????????????");
package BST;
public class Node {
int data;
Node leftChild;
Node rightChild;
public void displayNode(){
System.out.println("The data is " + this.data);
}
}
class Tree{
private Node root;
public Tree(){
this.root = null;
}
public Node find(int key){
Node current = root;
while(current.data != key){
if(key < current.data){
current = root.leftChild;
}
else{
current = root.rightChild;
}
if(current == null){
System.out.println("The Node contatining the key " + key + " does not exist!");
return null;
}
}
return current;
}
public void insert(int key){
Node newNode = new Node();
if(root == null){
root = newNode;
}
else{
Node current = root;
Node parent;
while(true){
parent = current;
if(current.data > key){
current = current.leftChild;
if(current == null){
parent.leftChild = newNode;
return;
}
}
else{
current = current.rightChild;
if(current == null){
parent.rightChild = newNode;
return;
}
}
}
}
}
public Node findMin(){
if(root == null){
System.out.println("The tree is empty!");
return null;
}
else{
Node current = root.leftChild;
Node last = root;
while(current != null){
last = current;
current = current.leftChild;
}
return last;
}
}
public Node findMax(){
if(root == null){
System.out.println("The tree is empty!");
return null;
}
else{
Node current = root.rightChild;
Node last = root;
while(current != null){
last = current;
current = current.rightChild;
}
return last;
}
}
public int countNodes(Node root){
int count = 0;
if(root == null){
System.out.println("The tree is empty!");
return -1;
}
else{
count = 1;
Node current = root;
if(current.leftChild != null){
count += countNodes(current.leftChild);
}
else if(current.rightChild != null){
count += countNodes(current.rightChild);
}
}
System.out.print("The total number of nodes in the tree is ");
return count;
}
Class MainTester
class MainTester{
public static void main(String[] args){
Tree tree1 = new Tree();
tree1.insert(1);
tree1.insert(2);
tree1.insert(3);
tree1.insert(4);
tree1.insert(5);
tree1.insert(6);
tree1.insert(7);
tree1.insert(8);
tree1.insert(9);
tree1.insert(10);
int countNodes = tree1.countNodes("?????????????");
}
}
You can use the root node of the tree. Basing from your example, you can get it from the method find()
int countNodes = tree1.countNodes(tree1.find(1));
You can also use other nodes like
int countNodes = tree1.countNodes(tree1.find(5));