https://oj.leetcode.com/problems/balanced-binary-tree/
判断一棵二叉树是不是平衡二叉树
方法比较笨拙。。。。
用到求深度的函数。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public static boolean isBalanced(TreeNode root) {
if(root==null)return true;
int left=root.left==null?0:depth(root.left);
int right=root.right==null?0:depth(root.right);
if(Math.abs(left-right)>1)return false;
return isBalanced(root.left)&&isBalanced(root.right);
}
public static int depth(TreeNode root){
if(root==null)return 0;
//if(root.left==null&&root.right==null)return 1;
int left=root.left==null?0:depth(root.left);
int right=root.right==null?0:depth(root.right);
return (left>right?left:right)+1;
}
}