给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
样例
给出二叉树 A={3,9,20,#,#,15,7}
, B={3,#,20,15,7}
A) 3 B) 3
/ \ \
9 20 20
/ \ / \
15 7 15 7
二叉树A是高度平衡的二叉树,但是B不是
解题思路1:
由于需要每个子树的深度信息,所以需要增加一个最大深度函数,用来返回当前节点的最大深度,这个深度函数类似于Lintcode 97:二叉树的最大深度。然后再用高度差信息判断当前节点是否为平衡节点,是则继续向下判断,否则返回false.
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
public boolean isBalanced(TreeNode root) {
// write your code here
if(root == null)
return true;
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
if(Math.abs(leftDepth-rightDepth) > 1)
return false;
else
return isBalanced(root.left) && isBalanced(root.right);
}
private int maxDepth(TreeNode root){
if(root == null)
return 0;
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}
解题思路2:
利用全局变量保存结果,其余与上相同。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
public boolean isBalanced(TreeNode root) {
// write your code here
maxLength(root);
return res;
}
private boolean res = true;
public int maxLength(TreeNode root){
if(root == null)
return 0;
int l = maxLength(root.left);
int r = maxLength(root.right);
if(Math.abs(l - r) > 1)
res = false;
return Math.max(l, r) + 1;
}
}