LeetCode—110. Balanced Binary Tree

LeetCode—110. Balanced Binary Tree

题目

https://leetcode.com/problems/balanced-binary-tree/description/
判断一棵二叉树是否是平衡二叉树。
平衡二叉树指的是,两棵子树的任一节点的深度相差不超过1.
在这里插入图片描述

思路及解法

首先写一个函数用来得到每一个子树的深度,然后递归调用原函数,判断两棵子树的深度差是否超过1

思路是这样的:分为两步。第一步判断每一个节点的左右子树深度是不是相差超过1;第二步遍历每一个节点,是不是符合第一步的条件要求,用递归的方法

代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null) return true;
        int leftDepth = getDepth(root.left);
        int rightDepth = getDepth(root.right);
        if(Math.abs(leftDepth-rightDepth)>1) return false;
        else return isBalanced(root.left)&&isBalanced(root.right);
    }
    public int getDepth(TreeNode node){
        if(node==null) return 0;
        else if(node.left==null && node.right==null) return 1;
        else{
            int leftDepth = getDepth(node.left);
            int rightDepth = getDepth(node.right);
            return 1+(leftDepth>rightDepth?leftDepth:rightDepth);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值