美文网首页ACM题库~
LeetCode 110. Balanced Binary Tr

LeetCode 110. Balanced Binary Tr

作者: 关玮琳linSir | 来源:发表于2017-10-01 17:09 被阅读32次

    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,那么就是平衡二叉树。

    java代码:

    
    public static boolean isBalanced(TreeNode root) {  
        if (root == null)  
            return true;  
        int distance = getDeep(root.left) - getDeep(root.right);  
      
        if (distance > 1 || distance < -1)  
            return false;  
        else  
            return isBalanced(root.left) && isBalanced(root.right);  
    }  
      
    // 最大深度  
    public static int getDeep(TreeNode root) {  
        if (root == null)  
            return 0;  
        int level = 0;  
        LinkedList<TreeNode> list = new LinkedList<TreeNode>();  
        list.add(root);  
        int first = 0;  
        int last = 1;  
        while (first < list.size()) {  
            last = list.size();  
            while (first < last) {  
                if (list.get(first).left != null) {  
                    list.add(list.get(first).left);  
                }  
                if (list.get(first).right != null) {  
                    list.add(list.get(first).right);  
                }  
                first++;  
            }  
            level++;  
        }  
        return level;  
    }
    

    相关文章

      网友评论

        本文标题:LeetCode 110. Balanced Binary Tr

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