剑指offer-39:平衡二叉树

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

解题思路

在做这题是,我第一反应就是遍历两次二叉树。第一遍记录每个节点的深度,并将信息存入HashMap中,key = node,value = depth。第二遍再遍历一次二叉树,同时判断每个节点是不是都是平衡二叉树。但这个方法并不是最优的,没有进行剪枝,增加了不少不必要的开销,而且使用了更多的额外空间。

private HashMap<TreeNode, Integer> nodeDepth = new HashMap<>();
private boolean flag = true;

public boolean IsBalanced_Solution(TreeNode root) {
    if (root == null) {
        return true;
    }
    if (flag) {
        depth(root);
        flag = false;
    }
    int depthLeft = nodeDepth.get(root.left) == null ? -1 : nodeDepth.get(root.left) ;
    int depthRight = nodeDepth.get(root.right) == null ? -1 : nodeDepth.get(root.right) ;
    return Math.abs(depthLeft - depthRight) < 2 && IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}

public int depth(TreeNode node) {
    if (node == null)   return -1;
    int d = Math.max(depth(node.left), depth(node.right)) + 1;
    nodeDepth.put(node, d);
    return d;
}

在提交完代码后,我看到解题思路分享里有一个更棒的方法,作者是丁满历险记。他的方法从下往上遍历,如果子树是平衡二叉树,则返回子树的高度;如果发现子树不是平衡二叉树,则直接停止遍历,这样至多只对每个结点访问一次。

public boolean IsBalanced_Solution(TreeNode root) {
    return getDepth(root) != -1;
}

public int getDepth(TreeNode node) {
    if (node == null) return 0;
    int left = getDepth(node.left);
    if (left == -1) return -1;
    int right = getDepth(node.right);
    if (right == -1) return -1;
    return Math.abs(left - right) > 1 ? -1 : Math.max(left, right) + 1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值