//利用递归返回的标记判断
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
return dfs(root) != -1;
}
private int dfs(TreeNode root){
if(root == null)
return 0;
int l = dfs(root.left);
if(l == -1) return -1;
int r = dfs(root.right);
if(r == -1) return -1;
return Math.abs(r - l) < 2 ? Math.max(r, l) + 1 : -1;
}
}
剑指 Offer 55 - II. 平衡二叉树 || 110. 平衡二叉树
最新推荐文章于 2021-07-02 09:09:19 发布