i am working to generate tango tree,
where i need to check whether every sub tree in tango is balanced or not.
if its not balanced i need to make it balance? I trying so hard to make entire RB-tree balance but i not getting any proper logic so can any one help me out??
here i am adding code to check how to find my tree is balanced are not but when its not
balanced how can i make it balance.
static boolean verifyProperty5(rbnode n) {
int left = 0, right = 0;
if (n != null) {
bh++;
left = blackHeight(n.left, 0);
right = blackHeight(n.right, 0);
}
if (left == right) {
System.out.println("black height is :: " + bh);
return true;
} else {
System.out.println("in balance");
return false;
}
}
public static int blackHeight(rbnode root, int len) {
bh = 0;
blackHeight(root, path1, len);
return bh;
}
private static void blackHeight(rbnode root, int path1[], int len) {
if (root == null)
return;
if (root.color == "black"){
root.black_count = root.parent.black_count+1;
} else{
root.black_count = root.parent.black_count;
}
if ((root.left == null) && (root.right == null)) {
bh = root.black_count;
}
blackHeight(root.left, path1, len);
blackHeight(root.right, path1, len);
}
Don't try to generate a tree and verify if it is balanced. Try to use a red-black structure from the start. It will guarantee that the resulting tree is balanced. Or did I misunderstood?
Edit:
It seems Tango tree is based on red black trees. Which means you need to have a red-black tree already implemented before implementing a Tango tree on top of that.
If you are looking for the red-black tree balancing, you can check out the code here.
Related
I have a binary tree where each node has the value of 0 or 1, and each path from the root to leaf node represents a binary string of a certain length. The aim of the program is to find all possible binary String (i.e. all possible paths from root to leaf). Now I want to parallelise it, so that it can use multiple cores. I assume I need to somehow split up the workload on the branch nodes, but I have no idea where to begin. I am looking at the ForkJoin functionality, but I have no idea how to split up the work and then combine it.
public class Tree{
Node root;
int levels;
Tree(int v){
root = new Node(v);
levels = 1;
}
Tree(){
root = null;
levels = 0;
}
public static void main(String[] args){
Tree tree = new Tree(0);
populate(tree, tree.root, tree.levels);
tree.printPaths(tree.root);
}
public static void populate(Tree t, Node n, int levels){
levels++;
if(levels >6){
n.left = null;
n.right = null;
}
else{
t.levels = levels;
n.left = new Node(0);
n.right = new Node(1);
populate(t, n.left, levels);
populate(t, n.right, levels);
}
}
void printPaths(Node node)
{
int path[] = new int[1000];
printPathsRecur(node, path, 0);
}
void printPathsRecur(Node node, int path[], int pathLen)
{
if (node == null)
return;
/* append this node to the path array */
path[pathLen] = node.value;
pathLen++;
/* it's a leaf, so print the path that led to here */
if (node.left == null && node.right == null)
printArray(path, pathLen);
else
{
/* otherwise try both subtrees */
printPathsRecur(node.left, path, pathLen);
printPathsRecur(node.right, path, pathLen);
}
}
/* Utility function that prints out an array on a line. */
void printArray(int ints[], int len)
{
int i;
for (i = 0; i < len; i++)
{
System.out.print(ints[i] + " ");
}
System.out.println("");
}
}
You can use Thread Pools to efficiently split the load between separate threads.
One possible approach:
ExecutorService service = Executors.newFixedThreadPool(8);
Runnable recursiveRunnable = new Runnable() {
#Override
public void run() {
//your recursive code goes here (for every new branch you have a runnable (recommended to have a custom class implementing Runnable))
}
};
service.execute(recursiveRunnable);
However, this approach is no longer a deep first search, since you list the sub-branches for your position before searching through the first one. In my understanding, DFS is a strictly linear approach and is therefore not entirely parallelizable (feel free to correct me in the comments though).
I was trying to solve this problem from leetcode and the prompt looks like this:
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/
class Solution {
public int kthSmallest(TreeNode root, int k) {
TreeNode curr = new TreeNode(0);
ArrayList<TreeNode> res = new ArrayList<TreeNode>();
res = inOrder(root);
if(res != null){
curr = res.get(k);
return curr.val;
}
return -1; //if not found
}
public ArrayList<TreeNode> inOrder(TreeNode root){ //the value of the nodes would be in increasing order
ArrayList<TreeNode> list = new ArrayList<TreeNode>();
if(root == null){
return list;
}
list.addAll(inOrder(root.left));
list.addAll(inOrder(root));
list.addAll(inOrder(root.right));
return list;
}
}
However, the system gave me the "memory limit exceeded" error message, is my logic faulted or is there anyway I could fix my code? Thanks in advance!
Your logic is probably fine, however should be an efficiency issue since you're getting MLE. It seems you're using two extra spaces, which we won't need that for solving this problem.
This'll pass in Java:
public final class Solution {
private static int res = 0;
private static int count = 0;
public final int kthSmallest(
final TreeNode root,
final int k
) {
count = k;
inorder(root);
return res;
}
private final void inorder(
final TreeNode node
) {
if (node.left != null)
inorder(node.left);
count--;
if (count == 0) {
res = node.val;
return;
}
if (node.right != null)
inorder(node.right);
}
}
and here is a Python version, if you'd be interested, similarly with inorder traversal:
class Solution:
def kthSmallest(self, root, k):
def inorder(node):
if not node:
return
inorder(node.left)
self.k -= 1
if self.k == 0:
self.res = node.val
return
inorder(node.right)
self.k, self.res = k, None
inorder(root)
return self.res
References
For additional details, please see the Discussion Board where you can find plenty of well-explained accepted solutions with a variety of languages including low-complexity algorithms and asymptotic runtime/memory analysis1, 2.
Brute force algorithms usually get accepted for easy questions. For medium and hard questions, brute force algorithms mostly fail with Time Limit Exceeded (TLE) and less with Memory Limit Exceeded (MLE) errors.
Aim: Find if a tree is a balanced binary tree.
I have implemented a program that does work, but wanted to make it more efficient by preventing unnecessary recursion. To do this I am using a static variable, that is set when even a single condition is evaluated to false, so that every other recursive call returns, before making any of their own recursive calls.
static int shouldIExit=0;
public boolean isBalanced(TreeNode root) {
if(root==null){
return true;
}
if(shouldIExit==1 || Math.abs(height(root.left)-height(root.right))>1){
height(root.right))>1: "+ (Math.abs(height(root.left)-height(root.right))>1) ) ;
shouldIExit=1;
return false;
}
else{
return (isBalanced(root.left) && isBalanced(root.right) );
}
}
The problem is that the static variable is somehow being set even when no condition causes it to do so. i.e., shouldIExit is set to 1 even when the if condition corresponding to it, does not evaluate to true.
Is this me not understanding how static variables work?
You don't need a static variable. It's usually bad practice to use non-local variables (either static or instance variables) in a recursive method.
public boolean isBalanced(TreeNode root) {
if(root==null) {
return true;
}
if(Math.abs(height(root.left)-height(root.right))>1) {
return false;
} else{
return (isBalanced(root.left) && isBalanced(root.right) );
}
}
You could save some work if you combine the logic of height and isBalanced. I believe something like this should work:
public boolean isBalanced (TreeNode root) {
return balancedHeight(root) >= 0;
}
public int balancedHeight (TreeNode root) {
if (root == null) {
return 0; // an empty tree is balanced
}
int left = balancedHeight(root.left);
if (left < 0) {
return -1; // left sub-tree is not balanced, so entire tree is not balanced
}
int right = balancedHeight(root.right);
if (left == right) { // the tree is balanced if both sub-trees are balanced
// and both have same height
return left + 1;
} else {
return -1; // tree is not balanced - either the right sub-tree is not
// balanced or the two sub-trees have different heights
}
}
I need to create a recursive method that takes as a parameter the root node of a binary search tree. This recursive method will then return the int value of the total number of nodes in the entire binary search tree.
This is what I have so far:
public class BinarySearchTree<E> extends AbstractSet<E>
{
protected Entry<E> root;
//called by the main method
public int nodes()
{
return nodes(root);
}
//nodes() will count and return the nodes in the binary search tree
private int nodes(Entry<E> current)
{
if(current.element != null)
{
if(current.left == null && current.right == null)
{
if(current.element == root.element)
return 1;
deleteEntry(current);
return 1 + nodes(current.parent);
}
else if(current.left != null && current.right == null)
return nodes(current.left);
else if(current.left == null && current.right != null)
return nodes(current.right);
else if(current.left != null && current.right != null)
return nodes(current.left) + nodes(current.right);
} else return 1;
return 0;
}
The main method calls nodes like so:
System.out.println ("\nThis section finds the number of nodes "
+ "in the tree");
System.out.println ("The BST has " + bst.nodes() + " nodes");
So I was running the search by traveling in order, once I'd get to a node with no children I would delete the current node and return to the parent node and continue. I ran a debug of the method I have above and the program crashes with a NullPointerException() when it finally counts and removes all the nodes on the left and right side of the root node and tries to return 1.
This is for my lab, the method MUST be recursive.
I'm very lost at this point, does anyone know what I'm doing wrong?
You are making this way too complicated. The basic idea of object oriented programming is that you trust objects to do the jobs they know the answers to. So if I'm a parent, I can count myself, and I let my children count themselves, and so forth.
private int nodes(Entry<E> current) {
// if it's null, it doesn't exist, return 0
if (current == null) return 0;
// count myself + my left child + my right child
return 1 + nodes(current.left) + nodes(current.right);
}
You have several issues:
You're deleting nodes as you count them? Is nodes() supposed to clear the tree?
You're treating root==null, root!=null&left==null&&right==null, root!=null&left!=null&right==null, etc as separate cases. They're not. You have three cases, which are not entirely exclusive:
If the current node is not null, add one to the count. (This should always be the case. The only case where it might be false is if the current node == root, and we can detect and sidestep that beforehand.)
If the current node has a left child, add the left child's count.
If the current node has a right child, add the right child's count.
You're traversing back up the tree for some ungodly reason. Looks like it has something to do with deleting nodes...?
But the biggest thing in my opinion is, you're not giving enough autonomy to the Entrys. :P
A node can count its own children. Trust it to.
class Entry<E> {
...
int count() {
int result = 1;
if (left != null) result += left.count();
if (right != null) result += right.count();
return result;
}
}
public int nodes() {
return (root == null) ? 0 : root.count();
}
If your teacher is incompetent, and insists on some node-counting function outside a node, you can do the same thing you were trying to do:
private int nodes(Entry<E> current) {
int result = 1;
if (current.left) result += nodes(current.left);
if (current.right) result += nodes(current.right);
return result;
}
public int nodes() {
return (root == null) ? 0 : nodes(root);
}
But that teacher should be fired, in my opinion. The Entry class is the real tree; BinarySearchTree is really just a container for a reference to the root.
Also notice, i don't give a damn about the parents. If we start counting from the root, and each node counts its children, which count their children, etc etc... then all nodes will be accounted for.
public int countNodes(Node root){
// empty trees always have zero nodes
if( root == null ){
return 0;
}
// a node with no leafes has exactly one node
// note from editor: this pice of code is a micro optimization
// and not necessary for the function to work correctly!
if( root.left == null && root.right == null ){
return 1;
}
// all other nodes count the nodes from their left and right subtree
// as well as themselves
return countNodes( root.left ) + countNodes( root.right ) + 1;
}
After you delete current in: deleteEntry(current);, you use current.parent in return 1 + nodes(current.parent);
May be this's the reason of throwing NullPointerException..
Hey I have a very clean counting implemented for a binary tree:
public class Binary<T> where T: IComparable<T>
{
private Node _root;
public int Count => _root.Count;
public void Insert(T item)
{
Node newNode = new Node(item);
if (_root == null)
_root = newNode;
else
{
Node prevNode = _root;
Node treeNode = _root;
while (treeNode != null)
{
prevNode = treeNode;
treeNode = newNode.Item.CompareTo(treeNode.Item) < 1 ? treeNode.Left : treeNode.Right;
}
newNode.Parent = prevNode;
if (newNode.Item.CompareTo(prevNode.Item) < 1)
prevNode.Left = newNode;
else
prevNode.Right = newNode;
}
}
public class Node
{
public T Item;
public Node Parent;
public Node Left;
public Node Right;
public Node(T item, Node parent = null, Node left = null, Node right = null)
{
Item = item;
Parent = parent;
Left = left;
Right = right;
}
public int Count
{
get
{
int count = 1;
count += Left?.Count ?? 0;
count += Right?.Count ?? 0;
return count;
}
}
}
}
Maybe this helps you to understand how to implement a class for a simple binary tree with a count.
This implementation accesses the count through a count in the corresponding node in the tree.
Let me now if you are not familiar with the markup of .NET 4.6
I have been trying to learn the ins and outs of some data structures and I am trying to get a binary splay tree to work properly. Every time I run the following code and the node I am looking for is more than one past the root it tells me it is there and then just deletes that whole side from the root down. It works fine if the node is only one level down from the top.
I am not sure what is going wrong but I suppose it has something to do with my rotate functions. I got it to work properly for the insert function which is what I modeled this after.
public class SplayBST {
Node root;
int count;
int level = 0;
boolean found = false;
public SplayBST() {
root = null;
count = 0;
}
public String searchIt(String x) {
//after finishing search method I need to check if splaySearch exists then don't insert just splay it
splaySearch(root, x);
if (this.found == true) {
this.found = false;
return x;
}
else {
return null;
}
}
Node splaySearch(Node h, String x) {
if (h == null) {
return null;
}
if (x.compareTo(h.value) < 0) {
try {
if (x.compareTo(h.left.value) < 0) {
h.left.left = splaySearch(h.left.left, x);
h = rotateRight(h);
} else if (x.compareTo(h.left.value) > 0) {
h.left.right = splaySearch(h.left.right, x);
h.left = rotateLeft(h.left);
}
else {
this.found = true;
return h.left;
}
return rotateRight(h);
}
catch (NullPointerException ex) {
return null;
}
}
else { //basically x.compareTo(h.value)>0
try {
if (x.compareTo(h.right.value) > 0) {
h.right.right = splaySearch(h.right.right, x);
h = rotateLeft(h);
} else if (x.compareTo(h.right.value) < 0) {
h.right.left = splaySearch(h.right.left, x);
h.right = rotateRight(h.right);
}
else {
this.found = true;
return h.right;
}
return rotateLeft(h);
}
catch (NullPointerException ex) {
return null;
}
}
}
Node rotateLeft(Node h) {
Node x = h.right;
h.right = x.left;
x.left = h;
return x;
}
Node rotateRight(Node h) {
Node x = h.left;
h.left = x.right;
x.right = h;
return x;
}
class Node {
Node left;
Node right;
String value;
int pos;
public Node(String x) {
left = null;
right = null;
value = x;
}
}
}
I second Tristan Hull's approach to creating a regular BST with a "working" search method. Once you get that working, adding a splay method is rather trivial. I've actually done the same thing when I implemented a Splay Tree in Java. It's a better software design and a simpler implementation.
Your problem is that when you rotate, you update the reference to node H in the function "SplaySearch", but you do not update the parent node in the original "searchIt" function. Thus, the program "thinks" that the original parent node remains the parent, even though the rotated node should be the parent. Thus, when you run whatever method you use to print your tree, you print from a node that is not actually the parent node of the tree, but a child (the level it is on depends on how many times your program called rotateLeft and rotateRight).
To fix this, I suggest implementing search as in a normal binary tree, and then making a "splay" function completely separate from the search function that splays a node to the top of the tree. You would call this splay function at the end of every search, making sure to properly update your reference. This is the traditional way to implement splay trees, and I suggest you take a look at it (maybe look at the wikipedia article on splay trees or do a Google search). Also, you may want to know that your rotate functions are not complete. In terms of splay trees, you also have 2 separate types of double rotations which are very different from single rotations. Again, I suggest looking up splay trees to learn about them more in depth.