127.Balanced Binary Tree

博客围绕判断二叉树是否为高度平衡展开。给出题目,即判断给定二叉树是否高度平衡,高度平衡指每个节点的两个子树深度相差不超1。还给出解答思路,如空树或单根节点是平衡的,根据左右子树高度差判断是否平衡等。

题目:

Given a binary tree, determine if it is height-balanced.

给定二叉树,确定它是否是高度平衡的。

For this problem, a height-balanced binary tree is defined as:

对于此问题,高度平衡二叉树定义为:

a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

一个二叉树,其中每个节点的两个子树的深度从不相差超过1。

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.

解答:

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public boolean isBalanced(TreeNode root) {
12         if(root==null)
13             return true;
14         return height(root)!=-1;
15     }
16     
17     public int height(TreeNode node){
18         if(node==null)
19             return 0;
20         int lH=height(node.left);
21         if(lH==-1)
22             return -1;
23         int rH=height(node.right);
24         if(rH==-1)
25             return -1;
26         if(lH-rH<-1||lH-rH>1)
27             return -1;
28         return Math.max(lH,rH)+1;
29     }
30 }

详解:

1.空树或只有根节点均为高度平衡的二叉树

2.如果左-右=0,-1,1均为高度平衡的二叉树,返回树的高度(左子树和右子树高度较大值+1)

3.如果左-右<-1或左-右>1,则不是高度平衡的二叉树,直接返回-1

转载于:https://www.cnblogs.com/chanaichao/p/9343887.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值