leetcode------Balanced Binary Tree

本文介绍了一种通过计算二叉树深度来判断其是否为平衡二叉树的方法。平衡二叉树定义为任意节点的两个子树深度相差不超过1。采用递归方式计算每个节点的左右子树深度,并对比深度差。
标题:
Balanced Binary Tree
通过率:32.3%
难度:简单

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.

平衡二叉树。这个可以由二叉树深度来计算,再二叉树深度计算中每次进行深度比较取深度较深的一个,那么平衡二叉树再比较深度时就是A-B绝对值超过一的话就不是二叉树了。立马返回-1 ,当左右子树有一边深度值是-1时立马终止,返回此树非平衡二叉树,如果A-B绝对值总是在0,1,-1三个数之中,那么继续深度递归判断,具体代码如下:

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

 

转载于:https://www.cnblogs.com/pkuYang/p/4171536.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值