LeetCode:平衡二叉树

187 阅读1分钟

一、题目描述

二、思路分析

2.1 分析

这题思路倒是挺简单的。平衡二叉树的定义是左右子树的高度差的角度值不能超过1。我们容易想到的思路就是先弄一个辅助函数,把左右子树的高度求出来,然后判断高度差是否符合平衡二叉树的定义。最后再递归判断左右子树是否是平衡二叉树。

2.2 图解

三、题解

/**
 * 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) {
        if (root == null) {
            return true;
        }
        /*[1,2,2,3,null,null,3,4,null,null,4]:必须保证左右子树也是平衡二叉树*/
        return isBalanced(root.left) && isBalanced(root.right) && Math.abs(getDepth(root.left) - getDepth(root.right)) <= 1;
    }

    private int getDepth(TreeNode node) {
        if (node == null) {
            return 0;
        }
        return 1 + Math.max(getDepth(node.left), getDepth(node.right));
    }
}