简介
使用递归判断是否是平衡二叉树
code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean b;
int dfs(TreeNode root, int level){
if(root == null){
return level;
}
int left = dfs(root.left, level+1);
int right = dfs(root.right, level+1);
if(Math.abs(left - right) > 1) b = false;
return Math.max(left, right);
}
public boolean isBalanced(TreeNode root) {
b = true;
dfs(root, 0);
return b;
}
}
---------------------------我的天空里没有太阳,总是黑夜,但并不暗,因为有东西代替了太阳。虽然没有太阳那么明亮,但对我来说已经足够。凭借着这份光,我便能把黑夜当成白天。我从来就没有太阳,所以不怕失去。
--------《白夜行》