LeetCode 110 平衡二叉树 递归

题目描述

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

链接:https://leetcode-cn.com/problems/balanced-binary-tree/

分析

可以用递归解决,思路就是判断左子树是否平衡、右子树是否平衡、还有左右子树高度差是不是1。

分析来源:LeetCode用户 但丁。

代码

class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;
        return isBalanced(root.left) && isBalanced(root.right) && Math.abs(depth(root.left) - depth(root.right)) <= 1;
    }
    
        private int depth(TreeNode root)
        {
            if (root == null) return 0;
            int leftDepth = depth(root.left);
            int rightDepth = depth(root.right);
            return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
        }
}

总结

我觉得最近反而对递归越来越不理解了,该去三连一波大神求解了。加油。

猜你喜欢

转载自blog.csdn.net/qq_40677350/article/details/91319261