本题用自顶向下递归和自底向上递归两种方法,后一种方法是最优解。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
自底向上递归:
class Solution {
/**
* 递归法
*/
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -1;
}
//求自身高度
private int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
//调用自身方法递归
int leftHeight = getHeight(root.left);
if (leftHeight == -1) {
return -1;
}
//调用自身方法递归
int rightHeight = getHeight(root.right);
if (rightHeight == -1) {
return -1;
}
// 左右子树高度差大于1,return -1表示已经不是平衡树了
if (Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}
return Math.max(leftHeight, rightHeight) + 1;
}
}
自顶向下递归:
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
// if (isBalanced(root.left) && isBalanced(root.right)) {
// return true;
// }
return !(Math.abs(depth(root.left) - depth(root.right)) > 1) && isBalanced(root.left) && isBalanced(root.right);
}
这里我的非递归测深度方法总是不对,没找出问题在哪,直接用了答案的方法。
// private int depth(TreeNode root) {
// if (root == null) {
// return 0;
// }
// int leftdepth = 0;
// int rightdepth = 0;
// TreeNode node = root;
// while (node != null) {
// leftdepth++;
// node = node.left;
// }
// while (node != null) {
// rightdepth++;
// node = node.right;
// }
// return Math.max(rightdepth,leftdepth)+1;
// }
public int depth(TreeNode root) {
if (root == null) {
return 0;
} else {
return Math.max(depth(root.left), depth(root.right)) + 1;
}
}
}