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.
public class TreeWeightBalanced
public static boolean isWeightBalanced(TreeNode root)
if (getBalancedHeight(root) == -1)
* 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)
int leftBalancedHeight = getBalancedHeight(root.getLeft());
int rightBalancedHeight = getBalancedHeight(root.getLeft());
if ((Math.abs(leftBalancedHeight - rightBalancedHeight) > 1) ||
(leftBalancedHeight == -1) || (rightBalancedHeight == -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 Median from Numbers Array - January 1, 2018
- Find Whether a Number Can Be the Sum of Two Squares - August 12, 2017
- How to Find Two Primes Whose Sum is Equal to a Number N - April 22, 2017
[…] our Binary Tree Implementation in Java, I put 5 mins of my time to make a small LinkedList class. Everything can be found in the […]