LeetCode110 Blanced Binary Tree Java 题解

原创 2015年07月06日 22:01:02

题目:

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

我们通过计算每一个节点的左右高度差  一旦发现有不满足的节点就将返回值置为-1   这两句代码if(left==-1) return -1;
if(right==-1) return -1保证只要出现一个高度差为-1的最终返回结果必然为-1,也就是说最终可以根据返回值是不是-1判断是不是平衡二叉树


代码:

public static boolean isBalanced(TreeNode root) {
		if(treeHight(root)==-1)
			return false;
		else 
			return true;
					
        
    }
	
	public static int treeHight(TreeNode root)
	{
		if(root==null)
			return 0;
		else {
			int left=treeHight(root.left);
			int right=treeHight(root.right);
			if(left==-1) return -1;
			if(right==-1) return -1;
			if(Math.abs(left-right)>1)
				return -1;
			else {
				return 1+Math.max(treeHight(root.left), treeHight(root.right));
			}
		}
	}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

剑指offer 面试题39:判断平衡二叉树(LeetCode 110. Balanced Binary Tree) 题解

剑指offer 面试题39:判断平衡二叉树 提交网址:  http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=...

LeetCode110.Balanced Binary Tree题解

1. 题目描述Given a binary tree, determine if it is height-balanced. For this problem, a height-balanc...

LeetCode题解-110-Balanced Binary Tree

原题 原题链接:https://leetcode.com/problems/balanced-binary-tree/ 这个题目有一个很大的争议就是AVL的定义,我以为的AVL的定义一直是...

【LeetCode-面试算法经典-Java实现】【110-Balanced Binary Tree(平衡二叉树)】

【110-Balanced Binary Tree(平衡二叉树)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given a binary tree, determin...

[leetcode]: 110. Balanced Binary Tree

1.题目Given a binary tree, determine if it is height-balanced.For this problem, a height-balanced bina...

leetcode(110). Balanced Binary Tree

problem Given a binary tree, determine if it is height-balanced. For this problem, a height-b...

leetcode 110 Balanced Binary Tree

This problem is generally believed to have two solutions: the top down approach and the bottom up wa...

LeetCode 110. Balanced Binary Tree

1. 题目描述 Given a binary tree, determine if it is height-balanced. For this problem, a height-b...

LeetCode(110)Balanced Binary Tree

题目如下: 分析如下: 之前尝试一边计算深度,一边做判断,发现这是无法实现的。因为bool型的返回变量说明了返回值没有深度信息,而如果没有深度信息,那么就无法判断左子树和右子树的深度差是否为1.所...

<LeetCode OJ> 110. Balanced Binary Tree

110. Balanced Binary Tree Total Accepted: 100175 Total Submissions: 298232 Difficulty: Easy G...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)