详细见:leetcode.com/problems/balanced-binary-tree
Java Solution: github
package leetcode;
import tools.TreeNode辅助.TreeNode;
/*
* 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.
*/
public class P110_BalancedBinaryTree {
public static void main(String[] args) {
}
/*
* AC
* 1 ms
*/
static class Solution {
boolean isFalse = false;
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
zxwtry_count(root);
return ! isFalse;
}
int zxwtry_count(TreeNode root) {
if (isFalse) {
return 0;
}
if (root == null) {
return 0;
}
int left = zxwtry_count(root.left);
int right = zxwtry_count(root.right);
if (Math.abs(left - right) > 1) {
isFalse = true;
}
return Math.max(left, right) + 1;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/balanced-binary-tree
AC 6ms 54.31%
*/
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
#define bool int
typedef struct TreeNode stn;
typedef struct TreeNode * ptn;
int search(ptn root, int* b) {
int cut = 0, lc = 0, rc = 0;
if (root == NULL) return 0;
lc = search(root->left, b);
if (! (*b)) return 0;
rc = search(root->right, b);
cut = lc - rc;
if (cut < -1 || cut > 1) *b = 0;
if (! (*b)) return 0;
return lc > rc ? lc+1 : rc+1;
}
bool isBalanced(ptn root) {
int cut = 0, lc = 0, rc = 0, b = 1;
if (root == NULL) return 1;
lc = search(root->left, &b);
if (! b) return 0;
rc = search(root->right, &b);
if (! b) return 0;
cut = lc - rc;
return cut >= -1 && cut <= 1;
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/balanced-binary-tree
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月29日
@details: Solution: 82ms 70.51%
'''
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def search(self, n, sign):
if n == None or sign[0]: return 0
lc = self.search(n.left, sign)
rc = self.search(n.right, sign)
if abs(lc-rc) > 1: sign[0] = True
return max(lc, rc) + 1
def isBalanced(self, n):
"""
:type n: TreeNode
:rtype: bool
"""
if n == None: return True
sign = [False]
lc = self.search(n.left, sign)
if (sign[0]): return False
rc = self.search(n.right, sign)
if (sign[0]): return False
return abs(lc-rc) < 2