Java Binary Tree Main Method - java

I've got a class Node
class Node{
int val;
Node parent;
Node left;
Node right;
public Node (int val){
this.val = val;
}
}
And I have a few methods:
public class Tree{
public Node root = null;
void insertNodeSorted(Node x, Node tree) {
if (x.val < tree.val) {
if (tree.left == null) {
tree.left = x;
}
else
insertNodeSorted(x, tree.left);
}
else {
if (tree.right == null) {
tree.right = x;
}
else
insertNodeSorted(x, tree.right);
}
} // end insertNodeSorted
void deleteNodeSorted(Node x) {
if (root == null)
return;
else
root = deleteNodeSorted(x, root);
}
Node deleteNodeSorted(Node x, Node tree) {
if (x.val < tree.val)
tree.left = deleteNodeSorted(x, tree.left);
else if (x.val > tree.val)
tree.right = deleteNodeSorted(x, tree.right);
else
tree = replaceNodeSorted(tree);
return tree;
} // end deleteNodeSorted
// Additional Method
Node replaceNodeSorted(Node tree) {
if (tree.right == null)
tree = tree.left;
else if (tree.left == null)
tree = tree.right;
else
tree.right = findReplacement(tree.right, tree);
return tree;
} // end replaceNodeSorted
Node findReplacement(Node tree, Node replace) {
if (tree.left != null)
tree.left = findReplacement(tree.left, replace);
else {
replace.val = tree.val;
tree = tree.right;
}
return tree;
} // end findReplacement
And I'd like to compile the Tree, but I don't know what I exactly I need to write in the main method.
public static void main(String[] args){
Tree t = new Tree();
t.insertNodeSorted();
What do I have to write in the brackets in order to print the Tree? (I know I still have to add System.out.println(val); in the methods..)

You defined a variable holding the root node, so it is not necessary to pass the parameter tree for the method insertNodeSorted. You can use always the root node.
Add a method taking only one parameter.
public void insertNodeSorted(Node x) {
if (root == null) {
root = x;
return;
}
insertNodeSorted(x, root);
}
Define the other method with two parameters as private
private void insertNodeSorted(Node x, Node tree) {
...
}
Now you can insert elements as follow:
Tree t = new Tree();
t.insertNodeSorted(new Node(1));
t.insertNodeSorted(new Node(134));
t.insertNodeSorted(new Node(13));
t.insertNodeSorted(new Node(4));
...

Related

Binary Search tree code without the parameters?

I have the following code.
But it is expected to be without parameters for example sum() and i am not quite sure on how to fix that so that the code would still work. Could someone help me with that?
I would like change the code as little as possible.
is there a way to add it to the methods and the recall the recusive methods from that
import java.util.*;
public class BinarySearchTree {
private class BinaryNode {
private int element;
private BinaryNode left;
private BinaryNode right;
private BinaryNode(int element) {
this.element = element;
}
}
private BinaryNode root;
public void insert(int newNumber) {
// special case: empty tree
if (root == null) {
root = new BinaryNode(newNumber);
return;
}
BinaryNode parent = null;
BinaryNode child = root;
while (child != null) {
parent = child;
if (newNumber == child.element) {
//number already in tree
return;
} else if (newNumber < child.element) {
child = child.left;
} else {
child = child.right;
}
}
if (newNumber < parent.element) {
parent.left = new BinaryNode(newNumber);
} else {
parent.right = new BinaryNode(newNumber);
}
}
public int maximumRecursive(BinaryNode root) {
if (root.right == null)
return root.element;
return maximumRecursive(root.right);
}
public int maximumIterative() {
if (root == null) {
throw new NoSuchElementException();
}
BinaryNode current = root;
while (current.right != null)
current = current.right;
return (current.element);
}
public int height(BinaryNode root) {
if (root == null)
return 0;
return 1 + Math.max(height(root.left), height(root.right));
}
public int sum(BinaryNode root) {
if (root == null)
return 0;
return root.element + sum(root.left) + sum(root.right);
}
public String reverseOrder(BinaryNode root) {
if (root == null) {
return "";
}
return reverseOrder(root.right) + " " + ((Integer) root.element).toString() + " " + reverseOrder(root.left);
}
You can just overload your sum method, so you have the version with parameter, and without parameter. Make the one with parameter private, as that version should only be used during the recursive deepening (inside the class):
private int sum(BinaryNode root) {
if (root == null)
return 0;
return root.element + sum(root.left) + sum(root.right);
}
public int sum() {
return sum(root);
}
You can do a similar thing for the other methods that are recursive, and for that reason have a parameter. For instance, for height:
private int height(BinaryNode root) {
if (root == null)
return 0;
return 1 + Math.max(height(root.left), height(root.right));
}
public int height() {
return height(root);
}

How to populate the BST and also print it in Inorder way

I am trying this code to populate the BST and then print it in the InOrder traversal format. But the root node is not getting populated compiling wihtout any error and Output is : "root is empty", so how to correct this code so that my BST gets populated in the Node root.
I tried to make Node root as static I thought it might be the case that root node might not be accessible from each method but it is not working, tried to change the name of the Node but it is also not working.
import java.util.*;
import java.io.*;
import java.lang.*;
class Node{
int data; Node left; Node right;
public Node(int data) {
this.data = data;
left = null;
right = null;
}
}
public class insert_tree {
static Node root;
insert_tree() //constructor
{
root = null;
}
public void addNode(int value) { // public method is called by the object and this public method calls the private method in which the root is also passed.
root = add(root, value);
}
private Node add(Node node, int value) {
if(node == null) {
return node;
}
if(value < node.data) {
node.left = add(node.left, value);
}
else if(value > node.data) {
node.right = add(node.right, value);
}
else {
return node;
}
return node;
}
private void inOrder(Node node) {
// node = root;
if(node != null) {
inOrder(node.left);
System.out.print(node.data + " ");
inOrder(node.right);
}
else {
System.out.print("root is empty");
}
//return null;
}
public void inorder() {
inOrder(root);
}
private void printRoot(Node root) {
System.out.println(root.data);
}
public void print() {
printRoot(root);
}
public static void main(String args[]) {
insert_tree obj = new insert_tree();
obj.addNode(20);
obj.addNode(14);
obj.addNode(25);
obj.addNode(10);
obj.addNode(16);
obj.addNode(25);
obj.addNode(21);
obj.addNode(30);
//printing the tree
obj.inorder();
}
}
The output should be the inorder traversal of the tree.
public void addNode(int value) { // public method is called by the object and this public method calls the private method in which the root is also passed.
root = add(root, value);
}
private Node add(Node node, int value) {
if(node == null) {
node = new Node(value);
}
else if(value == node.data) {
node.data = value;
}
else if(value < node.data) {
node.left = add(node.left, value);
}
else {
node.right = add(node.right, value);
}
return node;
}

How to remove all evens in linked list java

How can I remove all the evens in a linked list in java? Other similar questions did not help me. I have a possible solution, but it seems too complicated. I'm not sure it even works.
public class Node {
public int value;
public Node next;
public Node (int val) {
value = val;
}
public Node removeNode (Node root) {
if (root == null || (root.next == null && isOdd(root.value))) {
return null;
}
Node deep = root;
while (deep.next != null) {
deep = deep.next;
}
if (isOdd(deep.value)) {
for (Node x = root; x != null; x = x.next) {
if (isOdd(x.next.value)) {
x.next = x.next.next;
}
}
} else {
for (Node x = root; x.next != null; x = x.next) {
if (isOdd(x.next.value)) {
x.next = x.next.next;
}
}
}
if (isOdd(root.value)) {
root = root.next;
}
return root;
}
public boolean isOdd (int val) {
return (val % 2 == 1);
}
How can I improve this solution?
First of all: The remove method should be in your LinkedList class, not in the Node class itself!
After that it's quite easy to just remove the the even ones:
public class LinkedList {
private Node root;
public void removeEvens() {
if (root == null) return;
// removing all even nodes after the root
Node prev = root;
while (prev.next != null) {
if (isEven(prev.next))
prev.next = prev.next.next; // next is even: delete it
else
prev = prev.next; // next is not even: proceed
}
// delete root if it's even
if (isEven(root))
root = root.next;
}
private boolean isEven(Node node) {
return node.value % 2 == 0;
}
}
You can add an element before root node. In that case you don't have to write code for check root node.
public class Node {
public int value;
public Node next;
public Node(){}
public Node (int val) {
value = val;
}
public static Node removeEvens (Node root) {
Node head = new Node();
head.next = root;
for (Node node = head; node.next!=null; node=node.next)
if (isEven(node.next))
node.next = node.next.next;
return head.next;
}
public static boolean isEven(Node node) {
return node.value % 2 == 0;
}
}

Mirroring a binary tree

I am trying to find the mirror image of a binary tree. Here is what I do so far:
import treetoolbox.*;
public class MirrorTree extends BinaryTree<String> {
public MirrorTree(String key) {
this(null, key, null);
}
public MirrorTree(MirrorTree left, String key, MirrorTree right) {
this.key = key;
this.left = left;
this.right = right;
root = this;
}
public MirrorTree mirrorSymmetricTree() {
if (root == null) {
return null;
}
final MirrorTree left = (MirrorTree) root.left;
right = root.right;
root.left = mirrorSymmetricTree(right);
root.right = mirrorSymmetricTree(left);
return (MirrorTree) root;
}
public static MirrorTree mirrorSymmetricTree(BinaryTree<String> t) {
return null;
}
}
What am I doing wrong? The problem should be in this part:
if (root == null) {
return null;
}
final MirrorTree left = (MirrorTree) root.left;
right = root.right;
root.left = mirrorSymmetricTree(right);
root.right = mirrorSymmetricTree(left);
return (MirrorTree) root;
But I think I am missing something.
Delete this function:
public static MirrorTree mirrorSymmetricTree(BinaryTree<String> t) {
return null;
}
Add the parameter to this function to make it recursive:
public MirrorTree mirrorSymmetricTree(BinaryTree<String> t) {
if (root == null) {
return null;
}
final MirrorTree left = (MirrorTree) root.left;
right = root.right;
root.left = mirrorSymmetricTree(right);
root.right = mirrorSymmetricTree(left);
return (MirrorTree) root;
}
Your problem is here:
public static MirrorTree mirrorSymmetricTree(BinaryTree<String> t) {
return null;
}
you are not doing anything in this method!
Assuming you are using a BinaryTree<E> similiar to this documentation
You can see live version of my solution
This is how BinaryTree<E> is built where BinaryTree<E> is the Binary-Tree node itself, and every node in the tree is a tree by itself. This is how the insert method for BinaryTree<E> looks like
public void insert(T value)
{
if (this.value == null)
{
this.value = value;
return;
}
else
{
if (this.value.compareTo(value) >= 0)
{
if (this.left == null)
this.left = new BinaryTree<T>(value);
else
this.left.add(value);
}
else
{
if (this.right == null)
this.right = new BinaryTree<T>(value);
else
this.right.add(value);
}
}
}
Here is how the recursive function look like
private void mirrorSymmetricTree(MirrorTreeNode<T> m, BinaryTreeNode<T> n)
{
if (n == null) // base case
{
return;
}
if (n.left != null)
{
m.left = new MirrorTreeNode<T>(n.left.value);
mirrorSymmetricTree(m.left, n.left);
}
if (n.right != null)
{
m.right = new MirrorTreeNode<T>(n.right.value);
mirrorSymmetricTree(m.right, n.right);
}
}
public static MirrorTree mirrorSymmetricTree(BinaryTree<T> t)
{
if (t == null)
{
return null;
}
if (t.root != null)
{
this.root = new MirrorTreeNode<T>(t.root.value);
mirrorSymmetricTree(this.root, t.root);
}
return this;
}
Where your MirrorTree node would look like this
class MirrorTreeNode<T extends Comparable<T>>
{
public T value;
public MirrorTreeNode<T> left;
public MirrorTreeNode<T> right;
public MirrorTreeNode<T> (T value)
{
this.value = value;
this.left = null;
this.right = null;
}
..
}
Then you can mirror a tree by calling mirrorSymmetricTree on a BinaryTree
BinaryTree<String> t1 = new BinaryTree<>();
t1.addAll({"D","B","F","A","C","E","G"});
// D
// B F
// A C E G
t1.printDFS();
// A, B, C, D, E, F, G
MirrorTree<String> t2 = new MirrorTree<>();
t2.mirrorSymmetricTree(t1);
// t2 is a copy of t1 now
t2.printDFS();
// A, B, C, D, E, F, G
Notes
In order to mirror a binary tree of size N, you have to visit every node in that tree once, thus mirroring a tree has time complexity of O(N)
In order to mirror a binary tree, the items you store has to be Comparable, meaning they can be compared to find out if this.value > input or this.value < input to decide where to put it in the tree
In order to make sure the items are Comparable, you either implement this manually, or you demand that template type has to implement Comparable<T> interface, which force T to have compareTo function that let you compare values\keys as if they were numbers, where A.compareTo(B) > 0 is equivlant to A > B

Problem calling multiple instances of a class in java

i have a problem calling multiple instance of a class that i have coded (Tree, TreeNode)
in the main method, the system would give the output c d j c d j even though both trees are obviously different trees.
if i were to separate both postOrder() calls(each called after the tree has been pushed in to the stack)
Stack<Tree> alphaStack = new Stack<Tree>();
TreeNode a = new TreeNode('i');
Tree tree = new Tree(a);
TreeNode newleft = new TreeNode('a');
TreeNode newright = new TreeNode('b');
tree.setLeft(a, newleft);
tree.setRight(a, newright);
alphaStack.push(tree);
Tree.postOrder(alphaStack.pop().getRoot());
TreeNode b = new TreeNode('j');
Tree newtree = new Tree(b);
TreeNode left = new TreeNode('c');
TreeNode right = new TreeNode('d');
newtree.setLeft(b, left);
newtree.setRight(b, right);
alphaStack.push(newtree);
Tree.postOrder(alphaStack.pop().getRoot());
the output would be a b i c d j.
Does this mean that my class is not being duplicated but instead being reused when i make new Trees?
Below is the code:
import java.util.Stack;
public class mast_score {
public static void main(String[] args){
Stack<Tree> alphaStack = new Stack<Tree>();
TreeNode a = new TreeNode('i');
Tree tree = new Tree(a);
TreeNode newleft = new TreeNode('a');
TreeNode newright = new TreeNode('b');
tree.setLeft(a, newleft);
tree.setRight(a, newright);
alphaStack.push(tree);
TreeNode b = new TreeNode('j');
Tree newtree = new Tree(b);
TreeNode left = new TreeNode('c');
TreeNode right = new TreeNode('d');
newtree.setLeft(b, left);
newtree.setRight(b, right);
alphaStack.push(newtree);
Tree.postOrder(alphaStack.pop().getRoot());
Tree.postOrder(alphaStack.pop().getRoot());
} }
code for TreeNode
public class TreeNode{
Object item;
TreeNode parent;
TreeNode left;
TreeNode right;
public TreeNode (Object item) {
this.item = item;
parent = null;
left = null;
right = null;
}
public TreeNode getParent(TreeNode current) throws ItemNotFoundException
{
if(current == null) throw new ItemNotFoundException("No parent");
if(current.parent == null) throw new ItemNotFoundException("This
is the root");
else return current.parent;
}
public TreeNode getLeft(TreeNode current) throws ItemNotFoundException
{
if(current == null) throw new ItemNotFoundException("No left or
right child");
if(current.left == null) throw new ItemNotFoundException("No left
child");
else return current.left;
}
public TreeNode getRight(TreeNode current) throws ItemNotFoundException
{
if(current == null) throw new ItemNotFoundException("No left or
right child");
if(current.right == null) throw new ItemNotFoundException("No
right child");
else return current.right;
}
public Object getElement() throws ItemNotFoundException {
if(this.item == null) throw new ItemNotFoundException("No such
node");
else return this.item;
} }
code for Tree class
import java.util.*;
public class Tree {
static TreeNode root;
int size;
public Tree() {
root = null;
}
public Tree(TreeNode root) {
Tree.root = root;
}
public TreeNode getRoot() {
return this.root;
}
public int getLvl(TreeNode node) {
return node.lvlCount;
}
public void setLeft(TreeNode node, TreeNode left) {
node.left = left;
}
public void setRight(TreeNode node, TreeNode right) {
node.right = right;
}
public static void postOrder(TreeNode root) {
if (root != null) {
postOrder(root.left);
postOrder(root.right);
System.out.print(root.item + " ");
} else {
return;
}
}
public static int getSize(TreeNode root) {
if (root != null) {
return 1 + getSize(root.left) +
getSize(root.right);
} else {
return 0;
}
}
public static boolean isEmpty(Tree Tree) {
return Tree.root == null;
} }
Your problem is here, in the Tree class:
static TreeNode root;
You should remove the word static, and replace Tree.root with this.root.
Adding the keyword static causes the variable root to be shared between all instances of Tree in your program, which is not what you want.

Categories

Resources