I am in the process of creating a binary tree for a project I've been working on where I insert people into a binary tree by name (the tree iterates through each character to determine which is bigger when inserting). Is there a way to make my tree search through the tree to find a person who match the name given to the program. This is my code so far
lass Node {
private String person;
private Node left;
private Node right;
public Node(String person) {
this.person = person;
left = null;
right = null;
}
//setters
protected void setLeft(Node left) {
this.left = left;
}
protected void setRight(Node right) {
this.right = right;
}
//getters
protected String getPerson() {
return person;
}
protected Node getLeft() {
return left;
}
protected Node getRight() {
return right;
}
}
public class BinaryTree {
private static Node root;
public BinaryTree() {
root = null;
}
public void insert(String person) {
root = insert(person, root);
}
//Check if node is leaf
public static boolean isLeaf() {
if(root.getLeft() == null && root.getRight() == null)
return false;
else
return true;
}
// Search tree for entered value
public static void searchTree(String search, Node tNode) {
// Not sure what to put into the part to make the method search through people in the tree
}
private Node insert(String person, Node tree) {
if(tree == null)
tree = new Node(person);
else {
int count = 1;
int x = 0;
while(person.toLowerCase().charAt(x) == tree.getPerson().toLowerCase().charAt(x) && count != tree.getPerson().length()) {
count = count + 1;
x = x + 1;
}
if(person.toLowerCase().charAt(x) != tree.getPerson().toLowerCase().charAt(x)) {
if(person.toLowerCase().charAt(x) < tree.getPerson().toLowerCase().charAt(x))
tree.setLeft(insert(person, tree.getLeft()));
else
tree.setRight(insert(person, tree.getRight()));
} else {
tree.setRight(insert(person, tree.getRight()));
}
}
return tree;
}
Can you please suggest how I should create a method to search through the tree
I Would suggest you to do these steps. These steps will give you a start.
Start from root and compare the Name to be searched with root using compareToIgnoreCase().
Depending upon the result move left or right.
Continue till either node becomes null or you find a match.
If you're trying to implement a binary search tree, you need to change the code in your setters to determine whether to add a person to the left or right node (by comparing the strings lexicographically) every time those methods are called. If the tree is not ordered, you'd have to search every node. When it's ordered, you'll be able to search in log n time.
Related
I have the following data structure:
This tree stores only characters in lowercase.
I'm trying to build a method that finds the longest word in the tree recursively.
I have difficulty to build this method that checks each branch of the nodes recursively.
Here the given classes I'm using, showing only the relevant methods:
public class Tree {
private final Node root;
public Tree() {
root = new Node('0');
}
private String getWordOfBranch(final Node[] nodes, final int i) {
if (nodes[i] == null) {
return "";
}
if (nodes[i].isLeaf()) {
return String.valueOf(nodes[i].getValue());
}
return nodes[i].getValue() + getWordOfBranch(nodes[i].children, i);
}
public class Node {
private final char value;
protected Node[] children;
public Node(final char value) {
this.value = value;
children = new Node[26];
}
public boolean isLeaf() {
for (final Node child : children) {
if (child != null) {
return false;
}
}
return true;
}
public char getValue() {
return value;
}
Well, in this case, you are only taking the word starting at a specific position i. What you should be doing is looping through all of the children and finding the longest word out of all of the children. Also, your node class should not be having a set amount of children, but instead a dynamically sized list of children, using something like an ArrayList to store the children, since each node does not have to have a specific set of children.
public class Node {
private final char value;
protected ArrayList<Node> children;
public Node(final char value) {
this.value = value;
children = new ArrayList<Node>();
}
public boolean isLeaf() {
for (final Node child : children) {
if (child != null) {
return false;
}
}
return true;
}
public char getValue() {
return value;
}
public ArrayList<Node> getChildren() {
return children;
}
public String getLargestWord(Node root) {
if (root.isLeaf()) {
return String.valueOf(root.getValue());
}
else {
String longest = "";
for (Node child : root.getChildren()) {
String longWordInChild = getLongestWord(child);
if (longWordInChild.length() > longest.length()) {
longest = longWordInChild;
}
}
return root.getValue() + longest;
}
}
I made some changes to your code.
First the Node class.
import java.util.ArrayList;
import java.util.List;
public class Node {
private final char value;
protected List<Node> children;
public Node(char letter) {
value = letter;
children = new ArrayList<>();
}
private static boolean isValidValue(Node node) {
boolean isValid = false;
if (node != null) {
char ch = node.getValue();
isValid = 'a' <= ch && ch <= 'z';
}
return isValid;
}
public boolean addChild(Node child) {
boolean added = false;
if (child != null) {
if (isValidValue(child)) {
boolean found = false;
for (Node kid : children) {
found = kid != null && kid.getValue() == child.getValue();
if (found) {
break;
}
}
if (!found) {
added = children.add(child);
}
}
}
return added;
}
public List<Node> getChildren() {
return children;
}
public char getValue() {
return value;
}
}
I used List for the children, rather than an array, because an array has a fixed size and a List does not.
Now the Tree class. Note that I added a main() method to the class just for testing purposes. The main() method creates the tree structure in the image in your question.
A tree data structure has levels and also has leaves. A leaf is a node in the tree that has no child nodes. Hence every leaf in your tree is the last letter of a word. The leaves at the highest level represent the longest words. (Note that the level of the root node in the tree is zero.)
import java.util.ArrayList;
import java.util.List;
public class Tree {
private int longest;
private List<String> words;
private Node root = new Node('\u0000');
public List<String> getWords() {
return words;
}
public Node getRoot() {
return root;
}
public void visit() {
visit(root, 0, new StringBuilder());
}
public void visit(Node node, int level, StringBuilder word) {
if (node != null) {
word.append(node.getValue());
List<Node> children = node.getChildren();
if (children.size() == 0) {
if (level > longest) {
longest = level;
words = new ArrayList<>();
}
if (level == longest) {
words.add(word.toString());
}
}
else {
for (Node child : children) {
word.delete(level, word.length());
visit(child, level + 1, word);
}
}
}
}
/**
* For testing only.
*/
public static void main(String[] args) {
Tree tree = new Tree();
Node root = tree.getRoot();
Node j = new Node('j');
root.addChild(j);
Node r = new Node('r');
root.addChild(r);
Node a = new Node('a');
j.addChild(a);
Node v = new Node('v');
a.addChild(v);
Node a2 = new Node('a');
v.addChild(a2);
Node a3 = new Node('a');
r.addChild(a3);
Node o = new Node('o');
r.addChild(o);
Node d = new Node('d');
a3.addChild(d);
Node n = new Node('n');
a3.addChild(n);
Node d2 = new Node('d');
n.addChild(d2);
Node u = new Node('u');
a3.addChild(u);
Node m = new Node('m');
u.addChild(m);
Node s = new Node('s');
o.addChild(s);
Node e = new Node('e');
s.addChild(e);
tree.visit();
System.out.println(tree.getWords());
}
}
Method visit(Node, int, StringBuilder) is the recursive method. It traverses every path in the tree and appends the characters in each node to a StringBuilder. Hence the StringBuilder contains the word obtained by traversing a single path in the tree - from the root to the leaf.
I also keep track of the node level since the highest level means the longest word.
Finally I store all the longest words in another List.
Running the above code produces the following output:
[java, rand, raum, rose]
I am trying to write a function in a binary search tree class that will return the number of nodes in the tree that have values greater than n in the form public int greater (int n). I figured it might be easier to store all the values in a list and then iterate over the list and increment count each time a number is found to be greater than n. How would I go about implementing this?
This is my class so far:
public class BST
{ private BTNode<Integer> root;
private int count = 0;
List<Integer> arr = new ArrayList<>();
private BST right = new BST();
private BST left = new BST();
public BST()
{ root = null;
}
public boolean find(Integer i)
{ BTNode<Integer> n = root;
boolean found = false;
while (n!=null && !found)
{ int comp = i.compareTo(n.data);
if (comp==0)
found = true;
else if (comp<0)
n = n.left;
else
n = n.right;
}
return found;
}
public boolean insert(Integer i)
{ BTNode<Integer> parent = root, child = root;
boolean goneLeft = false;
while (child!=null && i.compareTo(child.data)!=0)
{ parent = child;
if (i.compareTo(child.data)<0)
{ child = child.left;
goneLeft = true;
}
else
{ child = child.right;
goneLeft = false;
}
}
if (child!=null)
return false; // number already present
else
{ BTNode<Integer> leaf = new BTNode<Integer>(i);
if (parent==null) // tree was empty
root = leaf;
else if (goneLeft)
parent.left = leaf;
else
parent.right = leaf;
return true;
}
}
public int greater(int n){ //TODO
return 0;
}
}
class BTNode<T>
{ T data;
BTNode<T> left, right;
BTNode(T o)
{ data = o; left = right = null;
}
}
I would not use a list as temporary storage.
There is a concept called Tree Traversal allowing you to visit each node of your tree.
Here is some pseudo code:
preorder(node)
if (node = null)
return
visit(node)
preorder(node.left)
preorder(node.right)
The visit function here is executed exactly once at each node.
For a specialized traversal like the counting you described, you could just replace visit with the functionality you want, like:
if (node.data > n) {
count += 1
}
Even better would be if you implement a Preorder class which you can extend to provide it with a custom visit function.
I have a doubly linked list that simulates the behavior of a singly linked list. So I have a left, right and info but the left is always null. Something like this:
1 -> 2 -> 3 -> 4
What I want is to change it back into doubly without recreating the nodes, just by parsing the list and remaking the connections.
1 -> <- 2 -><- 3 -><- 4
I have
class Node {
private int info;
private Node left;
private Node right;
And my method:
static Node toDoublyLinked(Node root) {
if (root.getRight() != null) {
root.getRight().setLeft(root);
return toDoublyLinked(root.getRight());
}
return root;
}
Which doesn't work. It makes my program to throw stack overflow because when I connect 2 to 1, 1 already has connections to 2-> 3 -> 4 so it will start duplication that piece of list over and over which is not what I want.
Is there any solution to solving this?
void add(int info) {
Node s = new Node();
if (this.info == 0) {
this.info = info;
} else {
if (info < this.info) {
if (left != null) {
left.add(info);
} else {
s.setInfo(info);
this.left = s;
}
} else {
if (right != null) {
right.add(info);
} else {
s.setInfo(info);
this.right = s;
}
}
}
}
public int getInfo() {
return info;
}
public void setInfo(int info) {
this.info = info;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
#Override
public String toString() {
return "Node{" +
"info=" + info +
", left=" + left +
", right=" + right +
'}';
}
Ok after some more debugging, it seems that it does throw StackOverflow in the toDoublyLinked but in the toString method. Why is it even calling toString in that method? I'm not. Not explicitly at least. I can understand why the toString is wrongly made but even if I comment it, it still doesn't work properly.
public static void toDoublyLinked(Node node) {
Node current = node;
while (current.getRight() != null) {
current.getRight().setLeft(current);
current = current.getRight();
}
}
If you want recursion:
public static void toDoublyLinked(Node node) {
if (node.getRight() != null) {
node.getRight().setLeft(node);
toDoublyLinked(node.getRight());
}
}
but remember that, as I said before, since Java doesn't have tail recursion optimization, this WILL stack overflow on long lists even though it's technically and ideologically correct;
You should not use recursion that will cause Stack Overflow over long lists.
What you should do instead is use an iterative method such as:
public static void toDoublyLinked(Node node){
Node currentNode = node ;
while(currentNode.getRight() !=null){
currentNode.getRight().setLeft(currentNode);
currentNode = currentNode.getRight();
}
}
This way, your code will not cause a stack overflow no matter the length of the list. Sure you have an additional variable but you will avoid the stack overflow with long lists AND improve the complexity (calling a function costs more).
However, if you still want to only use recursion (even though you should not), here is a piece of code:
public static void toDoublyLinked(Node node) {
if (node.getRight() != null) {
node.getRight().setLeft(node);
toDoublyLinked(node.getRight());
}
}
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
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)