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
Related
I'm learning the BST implementation, this is my code for insertion and inorder function. I have a doubt regarding the inorder function
public class BSTtry {
Node root;
class Node{
int data;
Node left,right;
Node(int data){
this.data=data;
left=right=null;
}
}
public void insert(int data) {
root=insertdata(root,data);
}
public void inorder(){
printinorder(root);
}
public Node insertdata(Node root,int data) {
if(root==null) {
root=new Node(data);
return root;
}
if(data<root.data) {
root.left=insertdata(root.left,data);
}
if(data>root.data) {
root.right=insertdata(root.right,data);
}
return root;
}
public void printinorder(Node root) {
if(root!=null) {
printinorder(root.left);
System.out.print(root.data+" ");
printinorder(root.right);
}
}
public static void main(String[] args) {
BSTtry bst=new BSTtry();
//Inserted some values in the tree
bst.printinorder(root);
}
}
So when I try to use the bst.printinorder(root); an error is thrown Cannot make a static reference to the non-static field root.
So can I change the root to static or print the inorder by calling the inorder() function.Which is a better way??
Main methods are static, root is a field of BSTtry.
Yes you could change the field to static but that's not what you want.
You should initialize the field e.g with a setter or with an constructor, having a Node argument.
Best regards
Just use inorder() instead, which calls printinorder() with root as the first argument.
bst.inorder();
Remove Node class out of BSTtry Class,
it will work
class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
}
public class BSTtry {
Node root;
public void insert(int data) {
root = insertdata(root, data);
}
public void inorder() {
printinorder(root);
}
public Node insertdata(Node root, int data) {
if (root == null) {
root = new Node(data);
return root;
}
if (data < root.data) {
root.left = insertdata(root.left, data);
}
if (data > root.data) {
root.right = insertdata(root.right, data);
}
return root;
}
public void printinorder(Node root) {
if (root != null) {
printinorder(root.left);
System.out.print(root.data + " ");
printinorder(root.right);
}
}
public static void main(String[] args) {
BSTtry bst=new BSTtry();
//Inserted some values in the tree
Node a = new Node(1);
a.left = new Node(2);
bst.printinorder(a);
}
}
So I¨m building a small game in which I want a search tree with all the possible moves. I¨m having some difficulties implementing the search tree however. I have managed to build a function that can calculate the move but then I¨m not sure how to build the tree, it should be recursivly. Each node should have a list with all possible moves.
public class Tree {
private Node root;
private int level;
public Tree(int level, Board board) {
this.level = level;
root = new Node(board);
}
public void add(Board board) {
int newLevel = board.numberPlacedDiscs();
if(newLevel>level){
//Add this at a new level.
Node newNode =new Node(board);
newNode.setParent(root);
root = newNode;
}else{
//add at this level.
root.addChild(new Node(board));
}
}
}
public class Tree {
private Node root;
private int level;
public Tree(int level, Board board) {
this.level = level;
root = new Node(board);
}
public void add(Board board) {
int newLevel = board.numberPlacedDiscs();
if(newLevel>level){
//Add this at a new level.
Node newNode =new Node(board);
newNode.setParent(root);
root = newNode;
}else{
//add at this level.
root.addChild(new Node(board));
}
}
}
As you can see I don't know how to add new Nodes. How do I know when to go down a level in the tree and add more nodes? Everytime a new disc is added to the board it should go down one level.
Here is a generic tree in Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TreeTest {
public static void main(String[] args) {
Tree tree = new Tree("root");
tree.root.addChild(new Node("child 1"));
tree.root.addChild(new Node("child 2"));
tree.root.getChild("child 1").addChild("child 1-1");
tree.root.getChild("child 1").addChild("child 1-2");
/*
root
-- child 1
---- child 1-1
---- child 1-2
-- child 2
*/
}
private static class Tree {
private Node root;
Tree(String rootData) {
root = new Node();
root.data = rootData;
root.children = new ArrayList<>();
}
public List<Node> getPathToNode(Node node) {
Node currentNode = node;
List<Node> reversePath = new ArrayList<>();
reversePath.add(node);
while (!(this.root.equals(currentNode))) {
currentNode = currentNode.getParentNode();
reversePath.add(currentNode);
}
Collections.reverse(reversePath);
return reversePath;
}
}
static class Node {
String data;
Node parent;
List<Node> children;
Node() {
data = null;
children = null;
parent = null;
}
Node(String name) {
this.data = name;
this.children = new ArrayList<>();
}
void addChild(String name) {
this.addChild(new Node(name));
}
void addChild(Node child) {
this.children.add(child);
}
void removeChild(Node child) {
this.children.remove(child);
}
public void removeChild(String name) {
this.removeChild(this.getChild(name));
}
public Node getChild(int childIndex) {
return this.children.get(childIndex);
}
Node getChild(String childName) {
for (Node child : this.children) {
if (child.data.equals(childName)) {
return child;
}
}
return null;
}
Node getParentNode() {
return this.parent;
}
}
}
blog post about generic tree data structure in java
Hope it helps
You can use this method to insert a Node into your tree:
private void insertNode(Node root, Node oldNode, Node newNode) {
if(root == null) {
return;
}
if(root == oldNode) {
oldNode.addChild(newNode);
return;
}
for(Node child : root.getChildren()) {
insertNode(child, oldNode, newNode);
}
}
So this method takes three parameters:
root - this is the root node of your tree.
oldNode - the node where you want to insert your newNode.
newNode - this is the node you want to be added to the children of your oldNode.
Node that if you pass a Node that does not exist in your tree, it will not throw any error. But you can modify to do it if you want.
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()));
}
I have a .class file named UBT.class (which i do not have access to the source code). I need to retrieve data from the UBT.class file. I have access to methods such as .getRoot() & .getLeft() & .getRight() from the UBT class (Not using the methods from the TreeNode class).
I tried writing an inOrder traversal method using recursion like this but its giving me errors like below although i specifiy it to be UBT not TreeNode
Error: incompatible types: TreeNode cannot be converted to UBT
//From main method
public static void inOrder(UBT root)
{
if(root.getRoot() != null)
{
inOrder(root.getRoot().getLeft());
System.out.println(root.getRoot().getData() + " ");
inOrder(root.getRoot().getRight());
}
}
class TreeNode
{
private int data;
private TreeNode left, right;
public TreeNode(int data) {
this.data = data;
this.left = null;
this.right = null;
}
public int getData() {
return data;
}
public void setData(int newData){
this.data = newData;
}
public TreeNode getLeft() {
return left;
}
public TreeNode getRight() {
return right;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public void setRight(TreeNode right) {
this.right = right;
}
}
class BST // Typical BST implementation
It looks like you want to split it up so your main recursion is on TreeNodes, not the UBT object.
public static void inOrder(TreeNode node) {
if(node != null)
{
inOrder(node.getLeft());
System.out.println(node.getData() + " ");
inOrder(node.getRight());
}
}
public static void inOrder(UBT root) {
if (root.getRoot() != null) {
inOrder(root.getRoot());
}
}
Using this, you'd call inOrder with your UBT, then it would grab the root TreeNode and do recursion on that with the TreeNode version of inOrder.
I have implemented a Binary search tree with insert and traversal method but am not getting correct output for PreOrder and Postorder ,am getting inOrder in correct order. Could some one please tell me where am wrong.
I tried the same example on paper but the PreOrder and PostOrder is not same.
Here is my Code
Node Class
package com.BSTTest;
public class Node implements Comparable<Node> {
private int data;
private Node leftChild;
private Node rightChild;
public Node(int data) {
this(data, null, null);
}
public Node(int data, Node leftChild, Node rightChild) {
this.data = data;
this.leftChild = leftChild;
this.rightChild = rightChild;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeftChild() {
return leftChild;
}
public void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
public Node getRightChild() {
return rightChild;
}
public void setRightChild(Node rightChild) {
this.rightChild = rightChild;
}
public int compareTo(Node o) {
return Integer.compare(this.data, o.getData());
}
}
Tree Class
package com.BSTTest;
import com.BSTTest.Node;
public class Tree {
private Node root = null;
public Node getRoot() {
return root;
}
//Inserting data**strong text**
public void insertData(int data) {
Node node = new Node(data, null, null);
if (root == null) {
root = node;
} else {
insert(node, root);
}
}
//Helper method for insert
private void insert(Node node, Node currNode) {
if (node.compareTo(currNode) < 0) {
if (currNode.getLeftChild() == null) {
currNode.setLeftChild(node);
} else {
insert(node, currNode.getLeftChild());
}
} else {
if (currNode.getRightChild() == null) {
currNode.setRightChild(node);
} else {
insert(node, currNode.getRightChild());
}
}
}
public void printInorder() {
printInOrderRec(root);
System.out.println("");
}
//Helper method to recursively print the contents in an inorder way
private void printInOrderRec(Node currRoot) {
if (currRoot == null) {
return;
}
printInOrderRec(currRoot.getLeftChild());
System.out.print(currRoot.getData() + ", ");
printInOrderRec(currRoot.getRightChild());
}
public void printPreorder() {
printPreOrderRec(root);
System.out.println("");
}
// Helper method for PreOrder Traversal recursively
private void printPreOrderRec(Node currRoot) {
if (currRoot == null) {
return;
}
System.out.print(currRoot.getData() + ", ");
printPreOrderRec(currRoot.getLeftChild());
printPreOrderRec(currRoot.getRightChild());
}
public void printPostorder() {
printPostOrderRec(root);
System.out.println("");
}
/**
* Helper method for PostOrder method to recursively print the content
*/
private void printPostOrderRec(Node currRoot) {
if (currRoot == null) {
return;
}
printPostOrderRec(currRoot.getLeftChild());
printPostOrderRec(currRoot.getRightChild());
System.out.print(currRoot.getData() + ", ");
}
//Main Mthod
public static void main(String[] args) {
Tree obj = new Tree();
//Inserting data
obj.insertData(3);
obj.insertData(5);
obj.insertData(6);
obj.insertData(2);
obj.insertData(4);
obj.insertData(1);
obj.insertData(0);
//printing content in Inorder way
System.out.println("Inorder traversal");
obj.printInorder();
//printing content in Inorder way
System.out.println("Preorder Traversal");
obj.printPreorder();
//printing content in Inorder way
System.out.println("Postorder Traversal");
obj.printPostorder();
}
}
Look my friend,your code is absolutely fine as the outputs you mentioned are absolutely correct.
I think you have not understood the concept of Binary Search Tree correctly.
You are right,3 is root node but you wrong in saying that 1 is its left child.
The first value that appears after 3 and that is smaller than 3 is 2,therefore 2 is left child of 3 and not 1
Refer to Cormenn book if still there is confusion.