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)

- Find Intersection Point of 2 Linked Lists in Java - November 20, 2016
- Check if a binary tree is a BST in Java - October 31, 2016
- Find repeated 10 char sequences in DNA sample - September 18, 2016

Pingback: implement a LinkedList in Java()