在leetcode刷题写了一版比较简洁的代码,分享给大家:
/**
* 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(Math.abs(Depth(root.left) - Depth(root.right)) <= 1)
return true && isBalanced(root.left) && isBalanced(root.right);
return false;
}
public int Depth(TreeNode treenode){
if(treenode == null) return 0;
return 1 + Math.max(Depth(treenode.left), Depth(treenode.right));
}
}
另外,空树是特殊的平衡二叉树,因此空树返回true。