110. Balanced Binary Tree

来源:互联网 发布:淘宝号怎么养 编辑:程序博客网 时间:2024/06/06 07:12
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
判断一棵树是否平衡
因为平衡的定义就是左右子树的高度差不超过1 所以要求高度
很直接的想法就是从根节点到叶子节点 逐个求左右高度 然后判断是否是平衡的 

class solution {public:    int depth (TreeNode *root) {        if (root == NULL) return 0;        return max (depth(root -> left), depth (root -> right)) + 1;    }    bool isBalanced (TreeNode *root) {        if (root == NULL) return true;                int left=depth(root->left);        int right=depth(root->right);                return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);    }};

但是这个过程中有大量重复计算 比如输入是
        1
    2        3
4    5    6    7
在判断1是否平衡时 求2的高的同时 也求了4,5的高度 
但是之后判断2是否平衡 还会计算4,5的高度

所以要修改成先求叶子节点是否平衡 然后向上传递高度 所以需要设定一个返回值 同时包含子树是否平衡 又包含子树高度的信息
实际上 我们只需要能区分开平衡和高度就可以了 
int就够了 当不平衡时返回-1 高度是不可能为负数的 

    public boolean isBalanced(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;        if (Math.abs(left-right) > 1) return -1;        return Math.max(left, right) + 1;    }

另外 getDepth可以写作
    private int getDepth(TreeNode root) {        if (root == null) return 0;        int left = getDepth(root.left);        int right = getDepth(root.right);        if (left == -1 || right == -1 || Math.abs(left-right) > 1) return -1;        return Math.max(left, right) + 1;    }


看上去会简洁一些 但实际上会增加计算量 比如 对于第一种写法 对于左子树不平衡的情况 是不需要求右子树的深度的
但是第二种写法 会求右子树的深度 所以第一种写法的效率高一些 相当于是失败快速返回的原则

直接写出了最优解 看了8个月之前的提交记录 提升不少 

原创粉丝点击