leetcode面试题0404_检查平衡性

382 阅读2分钟

题目:

LeetCode的面试题0404,题目地址

实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过 1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]
    3
   / \
  9  20
    /  \
   15   7
返回 true

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]
      1
     / \
    2   2
   / \
  3   3
 / \
4   4
返回 false

题解:

这个是考察二叉树的深度遍历的题目,主要是记录一下思路吧,难度并不大。 采用的是递归,将二叉树的节点都遍历了一次,然后要是发现了如果某个节点的左右子树的深度(或者用高度来计算也行) 只要差距是大于1的就是不平衡的。

class Solution {
    public boolean isBalanced = true;

    public boolean isBalanced(TreeNode root) {
        // 递归左子树和右子树的深度 相差大于1就不平衡
        getDepth(root, 0);
        return isBalanced;
    }

    private int getDepth(TreeNode node, int currentDepth) {
        if (node == null) {
            return 0;
        }
        int leftDepth = getDepth(node.left, currentDepth);
        int rightDepth = getDepth(node.right, currentDepth);
        // 不平衡
        if (Math.abs(leftDepth - rightDepth) > 1) {
            isBalanced = false;
            return -1;
        }
        // 左右两边的子树选最多深度的加一 就是当前节点的深度
        return Math.max(leftDepth, rightDepth) + 1;
    }
}

时间复杂度:o(n),每个节点都遍历了一次;
空间复杂度:1,使用了常数级的变量。

Tips:

稍微有一个小插曲就是isBalanced一开始我设置的是static的,单单去跑测试用例是可以跑通的,但是提交代码后。 会在测试用例[]出错,原本答案是true。但是之前的测试用例修改了isBalanced的值为false,所以报错了。 所以写leetcode最好不用使用static的变量。也是一个小点记录一下吧。

后记:

算法与数据结构的代码都放在github上了,github地址