110. 平衡二叉树

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

3
/
9 20
/
15 7
返回 true 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/balanced-binary-tree

 1 public class BalancedBinaryTree {
 2     static class TreeNode {
 3         int val;
 4         TreeNode left;
 5         TreeNode right;
 6         TreeNode(int x) {
 7             val = x;
 8         }
 9     }
10     private boolean result = true;
11     public boolean isBalanced(TreeNode root) {
12         @SuppressWarnings("unused")
13         int depth = maxDepth(root);
14         return result;
15     }
16     
17     public int maxDepth(TreeNode root) {
18         if(root == null) {
19             return 0;
20         }
21         int leftHigh = maxDepth(root.left);
22         int rightHigh = maxDepth(root.right);
23         if(Math.abs(leftHigh-rightHigh) > 1) {
24             result = false;
25         }
26         return Math.max(leftHigh, rightHigh) + 1;
27     }
28 }
无论有多困难,都坚强的抬头挺胸,人生是一场醒悟,不要昨天,不要明天,只要今天。不一样的你我,不一样的心态,不一样的人生,顺其自然吧
原文地址:https://www.cnblogs.com/xiyangchen/p/11065286.html