Implement a function to check whether the two fork tree is balanced, the balance is defined as follows, for any node in the tree, its two sub-tree height difference of not more than 1. Given a pointer to the root node treenode* root, return a bool, representing whether the tree is balanced.
ImportJava.util.*;/*Public class TreeNode {int val = 0; TreeNode left = null; TreeNode right = null; Public TreeNode (int val) {this.val = val; }}*/ Public classBalance { Public Booleanisbalance (TreeNode root) {if(Root = =NULL){ return true; } intLheight =treeheight (Root.left); intRheight =treeheight (root.right); if(lheight-rheight <= 1 && lheight-rheight >=-1){ returnIsbalance (Root.left) &&isbalance (root.right); } return false; } Public inttreeheight (TreeNode root) {if(Root = =NULL){ return0; } intLheight =treeheight (Root.left); intRheight =treeheight (root.right); returnLheight > Rheight? Lheight + 1:rheight + 1; }}
Binary Tree Balance Check