Given a binary tree, judge whether it is a highly balanced binary tree.
In this question, a height-balanced binary tree is defined as: the absolute value of the height difference between the left and right subtrees of each node of a binary tree does not exceed 1.
Example:
Given a binary tree [3,9,20,null,null,15,7]
returns: true
Given a binary tree [1,2,2,3,3,null,null,4,4]
return: false
Solution: Use recursion to judge the height of the node from bottom to top. If the difference between the height of the left subtree and the height of the right subtree of the node is greater than 1, the final return result is false, otherwise it returns true
class Solution {
public boolean isBalanced(TreeNode root) {
return DFS(root)==-1?false:true;
}
private int DFS(TreeNode node){
if(node==null){
return 0;
}
int left=DFS(node.left);
int right=DFS(node.right);
if(Math.abs(right-left)>1||left==-1||right==-1)
return -1;
else
return Math.max(left,right)+1;
}
}