题目描述
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
题目链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/
Java
/**
* 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 recur(root) != -1;
}
public int recur(TreeNode root) {
if(root == null) return 0;
int left = recur(root.left);
if(left == -1) return -1;
int right = recur(root.right);
if(right == -1) return -1;
return Math.abs(left - right) > 1 ? -1 : Math.max(left, right) + 1;
}
}
题解
对二叉树做后序遍历,从底到顶返回子树的深度,若一旦判定不是平衡树,则直接向上返回 -1。