leecode 110. 平衡二叉树

​​​​​​110. 平衡二叉树

        本题用自顶向下递归和自底向上递归两种方法,后一种方法是最优解。

/**
 * 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) {
        return getHeight(root) != -1;
    }

//求自身高度
    private int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
//调用自身方法递归
        int leftHeight = getHeight(root.left);
        if (leftHeight == -1) {
            return -1;
        }
//调用自身方法递归
        int rightHeight = getHeight(root.right);
        if (rightHeight == -1) {
            return -1;
        }
        // 左右子树高度差大于1,return -1表示已经不是平衡树了
        if (Math.abs(leftHeight - rightHeight) > 1) {
            return -1;
        }
        return Math.max(leftHeight, rightHeight) + 1;
    
    }
}


自顶向下递归:

class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;
        // if (isBalanced(root.left) && isBalanced(root.right)) {
        //     return true;
        // }
        return !(Math.abs(depth(root.left) - depth(root.right)) > 1) && isBalanced(root.left) && isBalanced(root.right);
    }
这里我的非递归测深度方法总是不对,没找出问题在哪,直接用了答案的方法。
    // private int depth(TreeNode root) {
    //     if (root == null) {
    //         return 0;
    //     }
    //     int leftdepth = 0;
    //     int rightdepth = 0;
    //     TreeNode node = root;
    //     while (node != null) {
    //         leftdepth++;
    //         node = node.left;
    //     }
    //     while (node != null) {
    //         rightdepth++;
    //         node = node.right;
    //     }
    //     return Math.max(rightdepth,leftdepth)+1;
    // }
    public int depth(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            return Math.max(depth(root.left), depth(root.right)) + 1;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值