Title Description
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.
Thought: Divide and conquer (means) recursion (processing method)
The code is as follows:
Import Java.util.*;/*public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; Public TreeNode (int val) { this.val = val; }} */public class Balance {public Boolean isbalance (TreeNode root) { if (root==null) return true; Boolean lef= isbalance (root.left); Boolean rig=isbalance (root.right); int leflength=deepth (root.left); int riglength=deepth (root.right); if (lef && rig && math.abs (leflength-riglength) <=1) return true; else return false; } int deepth (TreeNode root) { if (root==null) return 0; int leftdeepth=deepth (root.left); int rightdeepth=deepth (root.right); Return Math.max (leftdeepth,rightdeepth) +1;} }
12. Two Fork tree balance check