平衡二叉树(力扣习题)

给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
     //一个求深度的方法
       public int maxdepth(TreeNode root) {
        if(root==null) {
            return 0;
        }
        if(root.left==null&&root.right==null) {
            return 1;
        }
        int leftDepth = maxdepth(root.left);
        int rightDepth = maxdepth(root.right);
        return 1+(leftDepth>rightDepth?leftDepth:rightDepth);
    }
    public boolean isBalanced(TreeNode root) {
      if(root==null) {
          return true;//如果是null树,我们认为是平衡的
      }
      if(root.left==null&&root.right==null) {
          return true;//当是叶子节点也是平衡的
      }
      int leftDepth = maxdepth(root.left);
      int rightDepth = maxdepth(root.right);
      //判断左右子树深度大小不超过1
      return (leftDepth-rightDepth<=1&&leftDepth-rightDepth>=-1)&&isBalanced(root.left)&&            isBalanced(root.right);

    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45755718/article/details/105693908