LeetCode-------balanced-binary-tree

题目:

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 public class Solution {
 2     /*
 3     定义一个函数,用来求得这个二叉树的高度,利用递归方法
 4     */
 5     public int treeDepth(TreeNode root)
 6     {
 7         if(root == null)
 8         {
 9             return 0;
10         }
11         return 1+Math.max(treeDepth(root.left),treeDepth(root.right));
12     }
13     /*
14     上文我已经提到,但凡是遇到关于二叉树的相关操作我们第一个想到的就是递归,而后是队列和栈。
15     */
16     public boolean isBalanced(TreeNode root) {
17         if(root == null)//递归结束条件
18         {
19             return true;
20         }
21         int left = treeDepth(root.left);//计算左子树的高度
22         int right = treeDepth(root.right);//计算右子树的高度
23     /*
24     这个判断就是告诉我们以root为根节点的左右子树是平衡的,
25     而判断整个二叉树是否平衡,我们还要进行向下一层层的判断,这里就用到的了递归。
26     */
27         if(Math.abs(left-right)<=1)
28         {
29             if(isBalanced(root.left) == true && isBalanced(root.right) == true)
30             {
31                 return true;
32             }
33         }
34         return false;
35     }
36 }

 

转载于:https://www.cnblogs.com/cmh-hw/p/8029354.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值