Home » Problem Solving » How to implement a Binary Tree in Java

How to implement a Binary Tree in Java

I was thinking about writing a Binary Tree coding question and just realized I need a Binary Tree implementation in Java for that.

Explaining shortly – we will keep track of, Value, Right Node, Left Node, Size and Parent. We will see moving forward how these instance variables can help work for us in the Binary Tree implementation and we might add some more code in case we need some more helping methods for the Binary Tree.

Implement a Binary Tree in Java

/*
 * @Author: Ajk Palikuqi
 * 
 * @Question: How to implement a Binary Tree in Java. 
 * 
 */

package iqLib.treeLib;

public class TreeWeightBalanced
{
   public static boolean isWeightBalanced(TreeNode root)
   {
      if (getBalancedHeight(root) == -1)
      {
         return false;
      }

      return true;
   }

   /*
    * Given a TreeNode root, return the height of the tree under it if it is
    * balanced. Return -1 otherwise.
    */
   public static int getBalancedHeight(TreeNode root)
   {
      if (root == null)
      {
         return 0;
      }

      int leftBalancedHeight = getBalancedHeight(root.getLeft());
      int rightBalancedHeight = getBalancedHeight(root.getLeft());

      if ((Math.abs(leftBalancedHeight - rightBalancedHeight) > 1) || 
            (leftBalancedHeight == -1) || (rightBalancedHeight == -1))
      {
         return -1;
      }
      
      return Math.max(leftBalancedHeight, rightBalancedHeight);
   }
}

The actual code can be found here, in my GitHub repository, where I’ll be putting all my code from now on :).

Hope you guys enjoyed it and I’ll see you guys next time ;D

The following two tabs change content below.
If you like one of my posts the best way to support is give it a thumbs up, comment, or share it on social media :)

Latest posts by Ajk (see all)

%d bloggers like this: