每日一题6.10

近来一直在忙,每天做了题,没有及时更新博客。6.10的题目是与平衡二叉树有关的。

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

首先平衡二叉树是二叉搜索树的一种,中序遍历呈现出从小到大的排列。平衡二叉树是二叉搜索树的一种表达上的优化可以用最低的高度建造相应的二叉搜索树,其次平衡二叉树的一个特点就是左子树的高度与右子树的高度之差的绝对值是不大于1的。

利用这个思想,我们依次获取左右子树的高度,判定左右子树高度差,若二者差的绝对值大于1,则破坏了平衡二叉树的结构,因为平衡二叉树结构要求任意节点的子结构都是平衡二叉树结构。

一种方法是自顶向下去判定:

public classSolution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null) {
            return true;
        }
        return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 &&
            IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
    }
      
    private int maxDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }
}

因为自顶向下最后还需要返回到root节点,所以我们不妨直接自底向上的来解决这个问题:

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        return getDepth(root) != -1;
    }
     
    private int getDepth(TreeNode root) {
        if (root == null) return 0;
        int left = getDepth(root.left);
        if (left == -1) return -1;
        int right = getDepth(root.right);
        if (right == -1) return -1;
        return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(left, right);
    }
}

猜你喜欢

转载自blog.csdn.net/q_all_is_well/article/details/80676920