Mirror a binary tree - java

I have a simple Node class to construct a tree node in my binary tree:
class Node {
int data;
Node left;
Node right;
public Node(int i) {
this.data = i;
}
}
I've written a simple Tree class which will use the Node structure to build a tree:
class Tree {
Node root;
}
I'm trying to write a recursive function mirror() in my Tree class that will return a mirrored version of the tree (left and right nodes swapped).
So if I call this function on a Tree t, I would expect to start from the root, and swap all of the nodes until we reach a node that has no more children to swap. The part I'm struggling with is after we've swapped the root nodes children, how I can recursively call the mirror function on these nodes and then return the mirrored tree.
As you can see, the code below will swap the root node's children, but after that I am stuck as I can't call the mirror function on nodes, only a tree.
public Tree mirror() {
Node temp = this.root.left;
this.root.left = this.root.right;
this.root.right = temp;
If you could point me in the right direction I'd appreciate it.

You need a separate method that will accept Node object, mirror its children and call itself recursively.
public Tree mirror() {
mirrorInternal(this.root);
return this;
}
private void mirrorInternal(Node node) {
Node tmp = node.left;
node.left = node.right;
node.right = tmp;
if (node.left != null) {
mirrorInternal(node.left);
}
if (node.right != null) {
mirrorInternal(node.right);
}
}

I guess you could also change your Node-class such that it uses a flag for mirrored behavior:
class Node {
int data;
Node[] children;
public Node(int i) {
this.data = i;
this.children = new Node[2];
}
public void setLeft(Node node) {
children[0] = node;
}
public void setRight(Node node) {
children[1] = node;
}
public Node getLeft(boolean mirrored) {
return mirrored ? children[1] : children[0];
}
public Node getRight(boolean mirrored) {
return mirrored ? children[0] : children[1];
}
}

void mirror (Tree tree) {
mirror (tree.root);
}
Node mirror (Node node) {
if (node != null) {
Node temp = node.left;
node.left = mirror (node.right);
node.right = mirror (temp);
}
return node;
}

Related

Copy a Tree without parent reference [duplicate]

This question already has answers here:
How to deep copy a Binary Tree?
(7 answers)
Closed 3 years ago.
I want to create a recursive method which can copy a tree and return it as a Tree not a Node. This is the structure:
public class Tree {
Node root;
public Tree(Node root)
this.root = root;
}
public static class Node {
int key;
Node left;
Node right;
public Node(int key, Node left, Node right) {
this.key = key;
this.left = left;
this.right = right;
}
}}
public Tree copy() {
if(root == null)
return new Tree(null);
else {
return new Tree(copyRec(root));
}
}
private Node copyRec(Node node) {
if(node != null) {
Node curr = new Node(node.key, null, null);
curr.left = copyRec(node.left);
curr.right = copyRec(node.right);
return curr;
}
return null;
}

Is it possible to link multiple nodes to a single node?

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

Building a search tree in Java

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.

find object by id from nested object list in java

I have a java bean class :
class Node{
int id, parentId;
String value;
List<Node> childs;
}
How could i find a parent node in this hierarchy and insert a child node in the child list of parent node.
relationship between to node is defined as :
if node1.id == node2.parentid then node2 will be in child list of node1.
This can be Nth level hierarchy.
In order to find a node in that hierarchy, you'll have to implement a method for traversing. I suggest using a recursive method and employ either a breadth-first or depth-first search pattern. Once you've located the correct Node, insert the child.
For instance:
public Node search(Node root, int searchId) {
if (root.id == searchId) {
return root;
} else {
for (Node child : root.childs) {
Node node = search(child, searchId);
if (node != null) {
return node;
}
}
}
return null;
}
public void insert(Node node) {
Node parent = search(root, node.parentId);
if (node != null) {
parent.childs.add(node);
}
}
Try something like this
insertNode(Node nodeToInsert, Node anyNodeInHirarchy) {
Node parent = getParentNodeById(anyNodeInHirarchy.parentId);
if(parent.Id == nodeToInsert.parentId) {
parent.childs.add(nodeToInsert);
} else {
insertNode(nodeToInsert, parent)
}
}
return getParentNodeById(int nodeId) {
// Find node by id and return
return node;
}
easily :
childNode.setParentId(parentNode.getId());
parentNode.getChilds().add(childNode);
Fast way of doing it is
Guid should point the object easily so that you can point nth node easily.
Generate a Single Random GUID
for eg : say 45892
Root node will point to that id.
child will point in the pattern Parent_ID+"-"+Index_Number
If consider three child will have 45892-0, 45892-1, 45892-2
And child of first node becomes - 45892-0-1, 45892-0-2
So you can travel directly using the id as faster and need not search, search time will be saved.
If you don't understand please comment. I will show in programming.
Note : ID length grows as depends on your level of usage.
If you have data already in the db or some persistent store.then you can prefer jgitter code. if not you can prefer this.
class Node {
public String id;
public String parentId;
public List<Node> childs;
}
class Operation {
public Node getChildNodeByID(Node root,String parentId) {
String[] keys = parentId.split("-");
Node parentNode = root;
int index = 0;
for(String key : keys ) {
if(index == 0) {
if( !root.id.equals(key) ) {
throw new IllegalArgumentException("Root node does not match so parent node will not be found in this node");
}
}else {
int myIndex = Integer.parseInt(key);
if( parentNode.childs.getSize() > myIndex ) {
parentNode = parentNode.childs.get(myIndex);
}else {
throw new IllegalArgumentException("Parent Node does not exist");
}
}
index++;
}
return parentNode;
}
public insert(Node node,Node root) {
Node parentNode = getChildNodeByID(root,node.parentId);
node.id = node.parentId+"-"+parentNode.childs.getSize();
parentNode.childs.add(node);
}
}

Java binary tree add method over writes root

I am trying to write a binary tree and the add method is continually overwriting the root of the tree. I have two methods a recursive add method that takes in a String and a Node and then a regular add method that simply calls the recursive method. Any help would be greatly appreciated.
public Node recAdd(String event , Node tNode ){
//tNode -> tree node
if (tNode == null){
// Addition place found
root = new Node(event);
System.out.println("added root");
}
else if (tNode.event.compareTo(event) <= 0){
tNode.setLeft(recAdd(event, tNode.getLeft()));
// System.out.println("added left");// Add in left subtree
}
else{
tNode.setRight(recAdd(event, tNode.getRight()));
// System.out.println("added right");
}// Add in right subtree
return tNode;
}
//////////////////////////////////////////////
public void add(String event){
if(root != null){
System.out.println("The root currently is " + root.event );
}
recAdd(event , root);
}
And my node class is as follows
public class Node {
Node left;
Node right;
String event;
Node(String event){
this.event = event;
this.left = null;
this.right = null;
}
public void setEvent(String event){
this.event = event;
}
public void setLeft(Node left){
this.left = left;
}
public void setRight(Node right){
this.right = right;
}
public String getEvent(){
return event;
}
public Node getLeft(){
return left;
}
public Node getRight(){
return right;
}
}
You are replacing the root node whenever you find a spot to insert the current node:
public Node recAdd(String event, Node tNode) {
//tNode -> tree node
if (tNode == null) {
// Addition place found
root = new Node(event); // Problem is RIGHT HERE
System.out.println("added root");
}
//...
}
What's happening is that you recursively search through the tree until you reach a node that hasn't been assigned yet (i.e., it is null). At this point, you are overwriting root rather than creating the new node.
For example:
root
/ \
node null <- You want to assign this node, not overwrite root
/ \
null null
To do this:
public Node recAdd(String event , Node tNode ){
if (tNode == null){
tNode = new Node(event); // <--- Don't overwrite root
}
else if (tNode.event.compareTo(event) <= 0){
tNode.setLeft(recAdd(event, tNode.getLeft()));
}
else{
tNode.setRight(recAdd(event, tNode.getRight()));
}
return tNode;
}
You would also need to modify your add() function:
public void add(String event){
root = recAdd(event , root); // <-----Reassign root
}

Categories

Resources