Topic narrative:
Given a binary tree to determine whether it is a highly balanced binary tree.
In this problem, a well-balanced binary tree is defined as:
the absolute value of the difference between the height of the left and right subtrees a binary tree each node is not more than 1.
Ideas:
- Requires every node is a root node of a subtree are balanced
above problem is equivalent to the following two conditions:
1. For any one of the root node, its left subtree balance, the balance is also right subtree
2. about sub absolute difference is smaller than the height of the tree 2
Code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
if(root.left == null && root.right == null) return true;
return isBalanced(root.left)&&isBalanced(root.right)&&Math.abs(height(root.left)-height(root.right))<=1;
}
//求一棵树的高度
public int height(TreeNode root){
if(root == null) return 0;
return Math.max(height(root.left),height(root.right)) + 1;
}
}