Last active
December 12, 2018 12:14
-
-
Save juliofalbo/0c2af80a228d98659331347bbf540dfe to your computer and use it in GitHub Desktop.
Bidirectional Binary Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.uol.ps.so.api; | |
import java.util.ArrayList; | |
import java.util.List; | |
import lombok.AllArgsConstructor; | |
import lombok.Data; | |
/** | |
* @author Julio Falbo | |
* @version $Revision: $<br/> | |
* $Id: $ | |
* @since 12/12/18 09:17 | |
*/ | |
public class Main { | |
static List<Tree> database = new ArrayList<>(); | |
public static void main(String[] args) { | |
createTree(null, false, true); | |
createTree(1, false, true); | |
createTree(3, true, false); | |
changeParent(5, 4); | |
} | |
@Data | |
@AllArgsConstructor | |
static | |
class Tree { | |
Integer id; | |
Integer idParent; | |
Integer idRight; | |
Integer idLeft; | |
} | |
private static void createTree(Integer parentId, Boolean hasRight, Boolean hasLeft) { | |
final Tree root = new Tree(database.size() + 1, parentId, null, null); | |
database.add(root); | |
if (hasRight) { | |
final Tree right = new Tree(database.size() + 1, root.getId(), null, null); | |
database.add(right); | |
database.get(root.getId() - 1).setIdRight(right.getId()); | |
} | |
if (hasLeft) { | |
final Tree left = new Tree(database.size() + 1, root.getId(), null, null); | |
database.add(left); | |
database.get(root.getId() - 1).setIdLeft(left.getId()); | |
} | |
if (parentId != null) { | |
final Tree tree = database.get(parentId - 1); | |
insertNodeInEmptySpace(tree, root.getId()); | |
} | |
} | |
private static void insertNodeInEmptySpace(final Tree tree, final Integer id) { | |
if (tree.getIdLeft() != null && tree.getIdRight() != null) { | |
throw new RuntimeException("Parent tree is full"); | |
} | |
if (tree.getIdLeft() == null) { | |
tree.setIdLeft(id); | |
} else if (tree.getIdRight() == null) { | |
tree.setIdRight(id); | |
} | |
} | |
private static void changeParent(Integer currentTreeId, Integer newParentId) { | |
final Tree currentTree = database.get(currentTreeId - 1); | |
final Tree oldParent = database.get(currentTree.getIdParent() - 1); | |
if (oldParent.getIdLeft() != null && oldParent.getIdLeft().equals(currentTreeId)) { | |
oldParent.setIdLeft(null); | |
} | |
if (oldParent.getIdRight() != null && oldParent.getIdRight().equals(currentTreeId)) { | |
oldParent.setIdRight(null); | |
} | |
final Tree newParent = database.get(newParentId - 1); | |
insertNodeInEmptySpace(newParent, currentTreeId); | |
currentTree.setIdParent(newParentId); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment