前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode110 Balanced Binary Tree

leetcode110 Balanced Binary Tree

作者头像
用户1665735
发布2018-06-20 16:26:04
4190
发布2018-06-20 16:26:04
举报
文章被收录于专栏:kevindroidkevindroid

题目

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.

解题思路

很显然,解这道题需要从得到二叉树的高度的算法修改而来。 获取二叉树的高度的算法:

private int height(TreeNode node) {
        if (node == null) {
            return 0;
        } else {
            int i = height(node.left);
            int j = height(node.right);
            return (i < j) ? j + 1 : i + 1;
        }
    }

只需要修改下,让树的左右子树的高度差大于1时,返回-1.

public class leetcode110 {
    public boolean isBalanced(TreeNode root) {
        int res = helper(root);
        return res != -1;
    }

    private int helper(TreeNode node) {
        if (node == null) {
            return 0;
        } else {
            int i = helper(node.left);
            int j = helper(node.right);
            if (i == -1 || j == -1)
                return -1;
            else {
                if (Math.abs(i - j) > 1) return -1;
                else
                    return Math.max(i, j) + 1;
            }
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年05月06日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 解题思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档