110.平衡二叉树
思路:
本题想判断二叉树是否是平衡二叉树,那么就要判断 根节点 的左右子树高度差的绝对值是否 <= 1,判断完根节点的左右子树,此时需要进左子树中,判断左子树里的 根节点的左右子树高度差的绝对值是否 <= 1,依此类推,得出递归思路:
递归得到 左右子树高度,并判断高度差的绝对值是否 <= 1,判断完后左右子树还要再进左右子树继续进行高度判断。
- 递归终止条件:当节点为null,返回0
- 返回值为树的高度
- 单层逻辑为获得树的高度
代码实现
/**
* 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) {
if (root == null) return true;
return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
public int height(TreeNode root) {
if (root == null) return 0;
return Math.max(height(root.left), height(root.right)) + 1;
}
}