简介
使用递归判断是否是平衡二叉树
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;
}
}