美文网首页
110. 平衡二叉树

110. 平衡二叉树

作者: watermountain | 来源:发表于2019-04-02 15:24 被阅读0次

https://leetcode-cn.com/problems/balanced-binary-tree/

解一:

/**

* Definition for a binary tree node.

* public class TreeNode {

*    int val;

*    TreeNode left;

*    TreeNode right;

*    TreeNode(int x) { val = x; }

* }

*/

class Solution {

    public boolean isBalanced(TreeNode root) {

        if (root == null) {

            return true;

        }

        return isBalanced(root.left) &&

            isBalanced(root.right) &&

            Math.abs(deepth(root.left) - deepth(root.right)) <= 1;

    }

    private int deepth(TreeNode root) {

        if (root == null) {

            return 0;

        }

        return Math.max(deepth(root.left), deepth(root.right)) + 1;

    }

}

解二:

/**

* Definition for a binary tree node.

* public class TreeNode {

*    int val;

*    TreeNode left;

*    TreeNode right;

*    TreeNode(int x) { val = x; }

* }

*/

class Solution {

    public boolean isBalanced(TreeNode root) {

        if (root == null) {

            return true;

        }

        if (getHeight(root) == -1) {

            return false;

        }

        return true;

    }

    private int getHeight(TreeNode root) {

        if (root == null) {

            return 0;

        }

        int left = getHeight(root.left);

        int right = getHeight(root.right);

        if (left == -1 || right == -1) {

            return -1;

        }

        if (Math.abs(left - right) > 1) {

            return -1;

        }

        return Math.max(left, right) + 1;

    }

}

相关文章

网友评论

      本文标题:110. 平衡二叉树

      本文链接:https://www.haomeiwen.com/subject/jojgbqtx.html