题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路:
平衡二叉树任何一个节点的左右子树高度差不大于1,因此有一个左右子树求高度差的过程。所以存在两个递归,一个是高度的递归,另一个是高度差判断的递归。
java代码如下:
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null)
return true;
int high = tree_high(root.left) - tree_high(root.right);
if(high > 1 || high < -1)
return false;
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
int tree_high(TreeNode node){
if(node == null)
return 0;
return Math.max(tree_high(node.left), tree_high(node.right)) + 1;
}
}
结果:
运行时间:19ms
占用内存:9236k