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 }

 

posted @ 2019-06-21 16:18  往南的小燕子  阅读(112)  评论(0编辑  收藏  举报