思路
使用递归来求解。
1.确定递归函数的参数和返回值
参数为当前节点root,返回值为以当前参数为节点的二叉树的高度。
2.终止条件
当节点为null时,返回0;
3.每一层递归函数的意义
递归函数分别求得以当前节点为根节点,其左右子树的高度后,得到其差值,当差值大于1时,返回-1,,否则返回当前根节点的高度即子树高度最大值+1;
代码
/**
* 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 isBalanced(TreeNode root) {
if(root == null){
return true;
}
int res = fun(root);
return res!=-1;
}
public int fun(TreeNode root){
if(root == null){
return 0;
}
int left = fun(root.left);
if(left == -1){
return -1;
}
int right = fun(root.right);
if(right == -1){
return -1;
}
if(Math.abs(left - right)>1){
return -1;
}
return Math.max(right,left)+1;
}
}
|