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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
/* * @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 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