题目要求:
分析:
刚才看了那篇博客:三道题套路解决递归问题
这道题目在作者博客里提到,也是关于递归的,所以也就顺着作者的思路给做了。
由于这道题目比较特殊,就是又要判断是true还是false,又要根据高度差来判断,所以需要自己去创建一个类,让这个类既包含boolean类型,又包含int类型。
以下为作者原博客的分析:
具体代码为:
/**
* 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 class BandHeight {
boolean isBalanced;
int height;
public BandHeight(boolean isBalanced, int height) {
this.isBalanced = isBalanced;
this.height = height;
}
}
public boolean isBalanced(TreeNode root) {
return isBST(root).isBalanced;
}
public BandHeight isBST(TreeNode root) {
if(root == null)
return new BandHeight(true, 0);
BandHeight left = isBST(root.left);
BandHeight right = isBST(root.right);
if(left.isBalanced == false || right.isBalanced == false) {
return new BandHeight(false, 0);
}
if(Math.abs(left.height - right.height) > 1) {
return new BandHeight(false, 0);
}
return new BandHeight(true, Math.max(left.height, right.height)+1);
}
}
不说什么了,给那位写递归的作者鼓掌吧!👏👏👏