I am new to stack over flow so sorry for any mistakes, but i am trying to answer this question :
"Write a method that takes two binary trees t1, t2 and a binary tree node v as the arguments. It constructs and returns a new binary tree that has v as its root and whose left subtree is t1 and whose right subtree is t2."
I have done hours of attempts and cant seem to even make 1 binary tree.. The teacher wont really explain and wants us to do it using objects. This is the format she wants us to use.. Can someone please help me..
the commented out stuff is just my attempts to get something to work..
public class treeNode
{
private Object da;
private treeNode left;
private treeNode right;
public treeNode(Object newItem)
{
da = newItem;
left = null;
right = null;
}
public treeNode(Object newItem, treeNode leftNode, treeNode rightNode)
{
da = newItem;
left = leftNode;
right = rightNode;
}
public void setItem(Object newItem)
{
da = newItem;
}
public Object getItem()
{
return da;
}
public void setLeft(treeNode leftNode)
{
left = leftNode;
}
public treeNode getLeft()
{
return left;
}
public void setRight(treeNode rightNode)
{
right = rightNode;
}
public treeNode getRight()
{
return right;
}
//------------------------
public void buildTree()
{
}
//public void combine (l , r)
//{
// T = 5;
// setLeft(l);
// setRight(r);
// return T;
//}
//-----------------------
public static void main (String args [])
{
// treeNode a = new treeNode(5);
// treeNode b = new treeNode(8);
// treeNode c = new treeNode(2);
// a.setLeft(b);
// a.setRight(c);
// System.out.println(a.da);
// System.out.println(a.getLeft() );
// System.out.println(a.getRight() );
// treeNode t = new treeNode();
// t.left = t1;
// t.right = t2;
// System.out.println(buildTree(t));
}
}
My solution consists of two classes: Tree and Node.
The solution can be implemented with just Node, but since you were asked that the function will receive a two trees and a node so I implemented it like this. I don't know if you know java generics(The 'T' I used), if you don't, you can use Object like the code you posted. I'm ignoring all the getters and setters, but of course you can add them.
Node class:
public class Node<T> {
private T data;
private Node right;
private Node left;
public Node(T data) {
this.data = data;
}
public Node(T data, Node right, Node left) {
this.data = data;
this.right = right;
this.left = left;
}
}
Tree class:
public class Tree<T> {
private Node<T> root;
public Tree(Node root) {
this.root = root;
}
public Node<T> getRoot() {
return root;
}
}
The combine function:
public Tree combine(Tree t1, Tree t2, Node v) {
return new Tree(new Node(v, t1.getRoot(), t2.getRoot()));
}
Related
I created a method that is suppose to balance a BinarySearchTree.
The instructions were that the balance method should update the tree so that it is balanced, meaning that the largest difference between subtree heights is no more than 1.
With the following process:
• Get an array of sorted values in the tree (we have a method that can do this)
• Assign the tree's root to the result of the buildTreeUtil helper method (described below)
• Call assignFirst to update the tree's "first" attribute
The buildTreeUtil(E[], int, int, BSTNode parent) helper method rebuilds the tree using a sorted list of values. Since it has this sorted list, it doesn't have to search for where to insert new values, so it doesn't (and shouldn't) call the add method. Instead, it selectively grabs values from the sorted list of values when adding new nodes. It's algorithm is as follows:
• If the "start" parameter is greater than the "end" parameter, the recursion should stop
• Create a new node storing the middle element in the list
• Assign the new node's left reference to a recursive call using the left half of the list
• Assign the new node's right reference to a recursive call using the right half of the list
Here is the following code:
public void balance()
{
this.root = buildTreeUtil(toArray(), 0, size(), first);
assignFirst();
}
private BSTNode<E> buildTreeUtil(E[] values, int start, int end, BSTNode<E> parent)
{
if(start > end)
{
return null;
}
int mid = (start + end)/2;
BSTNode<E> node = new BSTNode<E>(values[mid]);
node.left = buildTreeUtil(values, start, mid - 1, parent.left);
node.right = buildTreeUtil(values, mid + 1, end, parent.right);
return node;
}
private void assignFirst()
{
if (root.left != null)
{
first.left = first;
}
else
{
first = root;
}
}
#SuppressWarnings("unchecked")
public E[] toArray()
{
ArrayList<E> aList = new ArrayList<E>();
E[] arr = (E[]) new Comparable[this.numElements];
toArray(this.root, aList);
return aList.toArray(arr);
}
private void toArray(BSTNode<E> node, List<E> aList)
{
if (node != null)
{
toArray(node.left, aList);
aList.add(node.data);
toArray(node.right, aList);
}
}
This is just the rest of my code cut short so there is some valuable background information.
public class BinarySearchTree<E extends Comparable<E>>
{
private BSTNode<E> root; // root of overall tree
private int numElements;
private BSTNode<E> first;
// post: constructs an empty search tree
public BinarySearchTree()
{
this.root = null;
this.numElements = 0;
}
public class Iterator
{
private BSTNode<E> currentNode;
public Iterator()
{
currentNode = first;
}
public boolean hasNext()
{
return currentNode != null;
}
public E next()
{
E value = currentNode.data;
currentNode = currentNode.next;
return value;
}
}
private static class BSTNode<E>
{
public E data;
public BSTNode<E> left;
public BSTNode<E> right;
public BSTNode<E> parent;
public BSTNode<E> next;
public BSTNode(E data)
{
this(data, null, null, null, null);
}
public BSTNode(E data, BSTNode<E> left, BSTNode<E> right, BSTNode<E> parent, BSTNode<E> next)
{
this.data = data;
this.left = left;
this.right = right;
this.parent = parent;
this.next = next;
}
}
}
I'm not sure where the error occurs or if I'm assigning the incorrect values inside the parameters for buildTreeUtil.
I'm trying to make a tree structure based on the linked list. Since linked list can only directly point to the next node(For singly linked list), I would like to modify the concept of the linked list. Is it possible to point at the one node from multiple nodes?
Here is an image in drawing
I think the following would work:
class Node {
Node sibling;
Node child;
Object item;
}
sibling will point to next Node at parallel level, child points to Node on lower level.
See below my implementation:
package treeTest;
public class Node {
private Node left;
private Node right;
private String data;
public Node(String data) {
this.data = data;
left = null;
right = null;
}
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;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
package treeTest;
public class Tree {
private Node root;
public Tree() {
root = null;
}
public void insert(String data) {
root = insert(root, data);
}
private Node insert(Node node, String data) {
if(node == null) {
// Then create tree
node = new Node(data);
} else {
if(data.compareTo(node.getData()) <= 0) {
node.setLeft( insert(node.getLeft(), data));
} else {
node.setRight(insert(node.getRight(), data));
}
}
return node;
}
}
package treeTest;
import java.util.Scanner;
public class TestTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
Tree tree = new Tree();
tree.insert("Hurricane");
// Second level
tree.insert("Cat1");
tree.insert("Cat2");
tree.insert("Cat3");
}
}
For more details checkout this Java Program to Implement a Binary Search Tree using Linked Lists
I wrote the following code to implement the recursive insert method for the BST. But when I print the tree in walk over order it prints the original tree before insertion. It seems as if the element was not inserted. Please help me out. Thanks in advance. Also please suggest the change in code. By the way, the intial tree in walk over order is 2 5 5 6 7 8.
package DataStructures;
class TreeNode {
private TreeNode parent;
private TreeNode childLeft;
private TreeNode childRight;
private int key;
public TreeNode(){
}
public TreeNode(int key) {
this(key, null);
}
public TreeNode(int key, TreeNode parent) {
this(key, parent, null, null);
}
public TreeNode(int key, TreeNode parent, TreeNode childLeft, TreeNode childRight) {
this.key = key;
this.parent = parent;
this.childLeft = childLeft;
this.childRight = childRight;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public TreeNode getParent() {
return parent;
}
public void setParent(TreeNode parent) {
this.parent = parent;
}
public TreeNode getChildLeft() {
return childLeft;
}
public void setChildLeft(TreeNode childLeft) {
this.childLeft = childLeft;
}
public TreeNode getChildRight() {
return childRight;
}
public void setChildRight(TreeNode childRight) {
this.childRight = childRight;
}
}
public class BinarySearchTreeBasicTest {
private static class BinarySearchTree {
private TreeNode root;
private TreeNode maxNode = new TreeNode(0);
public BinarySearchTree(TreeNode root) {
this.root = root;
}
public void printTheTreeInOrderWalk(TreeNode x) {
if (x != null) {
printTheTreeInOrderWalk(x.getChildLeft());
System.out.print(x.getKey() + " ");
printTheTreeInOrderWalk(x.getChildRight());
}
}
public void insertNode(TreeNode node, int key){
if (node == null){
node = new TreeNode(key);
}
else{
if (node.getKey() > key){
insertNode(node.getChildLeft(), key);
} else if (node.getKey() < key){
System.out.println("k");
insertNode(node.getChildRight(), key);
} else{
// dont do anything
}
}
}
}
public static void main(String[] args) {
TreeNode rootNode = new TreeNode(6);
BinarySearchTree tree = new BinarySearchTree(rootNode);
TreeNode node1 = new TreeNode(5);
TreeNode node2 = new TreeNode(7);
rootNode.setChildLeft(node1);
rootNode.setChildRight(node2);
node1.setParent(rootNode);
node2.setParent(rootNode);
TreeNode node3 = new TreeNode(2);
TreeNode node4 = new TreeNode(5);
node1.setChildLeft(node3);
node1.setChildRight(node4);
node3.setParent(node1);
node4.setParent(node1);
TreeNode node5 = new TreeNode(8);
node5.setParent(node2);
node2.setChildRight(node5);
tree.insertNode(rootNode, 3);
tree.printTheTreeInOrderWalk(rootNode);
}
}
In your insertNode() method, you are just creating a new node; you are never adding the newly created node to its parent. You should check whether you are going to insert here or not or you should return the newly returned node and set it accordingly.
If you don't want too much deviation from your current program, you can make the following changes.
public void insertNode(TreeNode node, int key) {
if (node.getKey() > key) {
if (node.left == null) { //check if you want to insert the node here
TreeNode newNode = new TreeNode(key);
node.left = newNode;
} else {
insertNode(node.getChildLeft(), key);
}
} else if (node.getKey() < key) {
if(node.right == null){ //check if you want to insert the node here
TreeNode newNode = new TreeNode(key);
node.right = newNode;
} else {
insertNode(node.getChildRight(), key);
}
} else {
// don't do anything
}
}
In Java, parameters are passed by value. In insertNode, if you don't do anything else with the node, the line node = new TreeNode(key); will not do anything useful.
The typical implementation of an insertion in a tree works by returning the TreeNode that will replace the previous one:
private TreeNode insertNode(TreeNode node, int key){
if (node == null){
node = new TreeNode(key);
}
else{
if (node.getKey() > key){
node.setChildLeft(insertNode(node.getChildLeft(), key));
} else if (node.getKey() < key){
node.setChildRight(insertNode(node.getChildRight(), key));
} else{
// dont do anything
}
}
return node;
}
Going a bit further, the previous method should actually be private. The public method should look like this:
public void insertNode(int key){
root = insertNode(root, key);
}
Here is the part of code of the binary tree class that I'm writing.
class Node<T> {
private T value;
private Node<T> left;
private Node<T> right;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public Node<T> getLeft() {
return left;
}
public void setLeft(Node<T> left) {
this.left = left;
}
public Node<T> getRight() {
return right;
}
public void setRight(Node<T> right) {
this.right = right;
}
public Node() {}
public Node(T value) {
this.value = value;
}
public Node(T value, Node<T> left, Node<T> right) {
this.value = value;
this.left = left;
this.right = right;
}
}
import java.util.*;
public class Tree<T extends Comparable<T>> {
private Node<T> root;
private List<T> levelOrderList = new ArrayList<T>();
public Node<T> getRoot() {
return root;
}
public Tree() {
}
public Tree(Node<T> root) {
this.root = root;
}
private List<T> getLevelOrderList(Node<T> root){
if (root == null)
return Collections.emptyList();
Queue<Node<T>> level = new LinkedList<Node<T>>();
level.add(root);
while(!level.isEmpty()){
Node<T> node = level.poll();
levelOrderList.add(node.getValue());
if(node.getLeft() != null)
level.add(node.getLeft());
if(node.getRight() != null)
level.add(node.getRight());
}
return levelOrderList;
}
public List<T> getLevelOrderList() {
return getLevelOrderList(root);
}
}
The method getLevelOrderList() returns list of elements in tree in level by level order.
The question is: how to rewrite method getLevelOrderList using recursion?
What you need to do is remove the loop, and just focus on a single pass through what now is in the loop. You'll need to move some of that code out of the private method and into the public method you created. Like the check for root == null, level instantiation, etc. Then you'll just keep calling the private method until level is empty. Here is how I'd change the signature:
public List<T> getLevelOrderList() {
if( root == null ) return Collections.emptyCollection();
List<Node<T>> level = new ArrayList<Node<T>>();
List<T> values = new ArrayList<T>();
level.add( root );
return getLevelOrderList( level, values );
}
private List<T> getLevelOrderList(List<Node<T>> level, List<T> values) {
if( level.isEmpty() ) return values;
// do the next step to visit the node at the head of the list and recurse
}
That should be enough to get you started, but I can't give this away since it's clearly homework. Oh and your program had a bug if you called getLevelOrderList() twice it would never clear out the instance variable you had so it would return double the number of items from the tree. By not using instance variables I removed that bug.
I am trying to create tree linked list in java and print Tree by levels of balls in metric spaces and I am unsuccessful.
create class ball:
public class Ball {
private double Point;
private double Radius;
public Ball(double Point, double Radius) {
this.Point = Point;
this.Radius = Radius;
}
public double getPoint() {
return Point;
}
public double getRadius() {
return Radius;
}
public void setPoint(double p)
{
this.Point=p;
}
public void setRadius(double r)
{
this.Radius=r;
}
public String toString(Ball b)
{
return b.Point+ " " + b.Radius;
}
}
and create class TreeNode
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class TreeNode<T> {
T data;
TreeNode<T> parent;
LinkedList<TreeNode<T>> children;
TreeNode next;
public TreeNode(T data ) {
this.data = data;
this.children = new LinkedList<TreeNode<T>>();
this.parent = null;
}
public TreeNode(T data , TreeNode<T> parent)
{
this.data=data;
this.parent=parent;
this.children = new LinkedList<TreeNode<T>>();
}
public TreeNode<T> addChild(T child)
{
TreeNode<T> childNode = new TreeNode<T>(child);
childNode.parent = this;
this.children.add(childNode);
return childNode;
}
public void setNext(TreeNode e)
{
this.next=e;
}
public TreeNode getNext()
{
return this.next;
}
public TreeNode <T> Insert(TreeNode<T> pos, T x)
{
TreeNode <T> tmp = new TreeNode <T>(x);
if(pos == null)
{
tmp.setNext(this.parent);
this.parent= tmp;
}
else{
tmp.setNext(pos.getNext());
}
return tmp;
}
public TreeNode<T> getParent() {
return parent;
}
public T getData() {
return data;
}
public LinkedList<TreeNode<T>> getChild ()
{
return children;
}
public void setData(T data1)
{
this.data=data1;
}
public void setParent(TreeNode<T> getParent)
{
this.parent=parent;
}
public String toString()
{
return this.data.toString() ;
}
}
In addition create class cover tree levels
my problem is insert element to tree
public class CoverTreeLevels {
static final int LEVELS = 25;
public static Data d;
public static void Insert(TreeNode node, TreeNode newNode)
{
newNode.parent=node.parent;
node.parent=newNode.parent;
}
public static void buildTree(double [][] data)
{
double rootRadius =d.Find_Max_Radiues(d.data);
Ball rootBall = new Ball(data[0][0], rootRadius);
TreeNode root = new TreeNode<Ball>(rootBall);
TreeNode last = root;
for (double i = 1, lastRadius = rootRadius / 2; i < LEVELS - 1; i++, lastRadius /= 2) {
Ball ball = new Ball( data[0][0] , lastRadius);
last = last.addChild(ball);
for (int j = 1; j < data.length; j++) {
TreeNode<Ball> n = last;
while (true)
{
if(d.dist(j, 0)> lastRadius)
{
Ball newBall = new Ball(data[j][0], lastRadius);
n.addChild(newBall) ;
}
n.getParent();
}
}
}
}
and class Data which includes data in metric spaces.
Am I headed in the right direction?
For one, it looks like you have some issues with access modifiers in this code.
Here, you're referencing private properties of these objects without using the getters/setters you specified. This will be a compiler error.
Second, your insert method seems to be setting the node.parent to itself.
public static void Insert(TreeNode node, TreeNode newNode)
{
newNode.parent=node.parent; // new node's parent is being set to current node's parent.
node.parent=newNode.parent; // current node's parent being set to newNode's parent, which you just assigned to node.parent above
}
To insert properly, you'd need to insert the newNode itself into the equation:
public static void Insert(TreeNode node, TreeNode newNode)
{
if ( node != null && newNode != null) {
TreeNode temp;
temp = node.getParent(); // get the current node's parent
node.setParent(newNode); // set the new parent of current node to newNode
newNode.setParent(temp); // set the new node's parent to current node's old parent
}
}
Now you should have a properly functioning insert.