给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
/**
* 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;
}
int leftDepth = treeDepth(root.left);
int rightDepth = treeDepth(root.right);
int num = Math.abs(leftDepth - rightDepth);
if(num > 1) {
return false;
} else {
return isBalanced(root.left) && isBalanced(root.right);
}
}
int dep = 0;
public static int treeDepth(TreeNode root){
if(root == null){
return 0;
}
int left = treeDepth(root.left);
int right = treeDepth(root.right);
return (left>right)?(left+1):(right+1);
}
}
网友评论