public class 平衡二叉树
{
    public class TreeNode
    {
        TreeNode left;
        TreeNode right;
        int val;

        TreeNode(int x)
        {
            this.val = x;
        }
    }

    // 获取深度
    private int getDepth(TreeNode tree, int currentDepth)
    {
        if (tree == null)
        {
            return currentDepth;
        }
        return Math.max(getDepth(tree.left, currentDepth + 1),
                getDepth(tree.right, currentDepth + 1));

    }

    // 采用递归解决
    public boolean isBalanced(TreeNode root)
    {
        if (root == null)
        {
            return true;
        }
        int depthOfLeft = getDepth(root.left, 1);
        int depthOfRight = getDepth(root.right, 1);
        if (Math.abs(depthOfLeft - depthOfRight) > 1)
        {
            return false;
        }
        else
        {
            return isBalanced(root.left) && isBalanced(root.right);
        }
    }
}

相关文章:

  • 2021-07-26
  • 2021-04-05
  • 2021-06-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-27
  • 2021-08-29
猜你喜欢
  • 2022-12-23
  • 2021-11-13
  • 2021-09-21
  • 2022-12-23
  • 2022-12-23
  • 2021-06-22
  • 2021-12-25
相关资源
相似解决方案