110.平衡二叉树

本文探讨了如何使用递归和迭代方法判断一棵二叉树是否高度平衡,通过实例展示了两种算法实现,包括递归求节点左右子树高度差并检查是否超过1,以及层序遍历比较每层节点高度的迭代法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

解法一:递归法,求每一个节点的左右子树高度,差值大于1就返回-1,-1作为标志判断最后的结果

class Solution {
    public boolean isBalanced(TreeNode root) {
        int result = dG(root);
        return result != -1 ? true:false;
    }

    public int dG(TreeNode node) {
        if (node == null) {
            return 0;
        }

        int leftHeight = dG(node.left);
        if (leftHeight == -1) {
            return -1;
        }

        int rightHeight = dG(node.right);
        if (rightHeight == -1) {
            return -1;
        }

        if (Math.abs(leftHeight - rightHeight) > 1) {
            return -1;
        }

        return Math.max(leftHeight,rightHeight) + 1;

    }
}

解法二:迭代法

①层序遍历求每个节点的高度

②比较每个节点的左右子树高度

    // 暴力迭代
    // 1.求子树高度 (因为root节点的深度和叶子节点的高度是一样,所以直接求root节点的深度了)
    static public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int height = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            height++;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
        }
        return height;
    }

    //2.比较左右节点的子树高度
    static public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (root.right == null || pre == root.right) {
                if (Math.abs(getHeight(root.left) - getHeight(root.right)) > 1) {
                    return false;
                }
                pre = root;
                root = null;
            } else {
                stack.push(root);
                root = root.right;
            }
        }
        return true;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值