LeetCode题解-110-Balanced Binary Tree

原题


原题链接:https://leetcode.com/problems/balanced-binary-tree/

这个题目有一个很大的争议就是AVL的定义,我以为的AVL的定义一直是“no 2 leaf nodes differ in distance from the root by more than 1”,与这个题目不同,所以一开始提交了错误的方法,但是查阅了资料发现LeetCode给出的定义应该才是正确的定义,请见https://discuss.leetcode.com/topic/276/two-different-definitions-of-balanced-binary-tree-result-in-two-different-judgments/2?show=63的讨论帖。


解法

解法分析

递归判断左子树是否是AVL,递归判断右子树是否为AVL,如果左右子树都是AVL,并且左右子树的高度差不超过1,那么这棵树为AVL。


代码

public class Solution110_recursive {
    public boolean isBalanced(TreeNode root) {
        return depth(root) != -1;
    }
    
    private int depth(TreeNode root){
        if (root == null)
            return 0;
        int depthOfLeft = depth(root.left);
        int depthOfRight = depth(root.right);

        if (depthOfLeft == -1 || depthOfRight == -1)
            return -1;
        if (Math.abs(depthOfLeft - depthOfRight) > 1)
            return -1;
        return Math.max(depthOfLeft, depthOfRight) + 1;
    }
}


no 2 leaf nodes differ in distance from the root by more than 1”的“AVL”的我的解法,未验证正确性。

解法分析

采用BFS,如果第i层未满并且第i+1层仍有节点,则非“avl”。

代码

public class Solution110_BFS_iterator {
    public boolean isBalanced(TreeNode root) {
        int expectSize = 1;
        boolean levelNotFull = false;
        Deque deque = new LinkedList();

        if (root != null)
            deque.push(root);

        while (!deque.isEmpty()){
            int exactSize = deque.size();

            if (levelNotFull == true && exactSize != 0)
                return false;
            if (exactSize != expectSize)
                levelNotFull = true;
            expectSize = expectSize * 2;

            while (exactSize-- > 0){
                TreeNode currentNode = deque.pop();
                if (currentNode.left != null)
                    deque.addLast(currentNode.left);
                if (currentNode.right != null)
                    deque.addLast(currentNode.right);
            }
        }
        return true;
    }
}

你可能感兴趣的:(LeetCode)