How to determine if binary tree is balanced?

前端 未结 27 1521
萌比男神i
萌比男神i 2020-11-30 16:11

It\'s been a while from those school years. Got a job as IT specialist at a hospital. Trying to move to do some actual programming now. I\'m working on binary trees now, a

27条回答
  •  青春惊慌失措
    2020-11-30 16:49

    If binary tree is balanced or not can be checked by Level order traversal:

    private boolean isLeaf(TreeNode root) {
        if (root.left == null && root.right == null)
            return true;
        return false;
    }
    
    private boolean isBalanced(TreeNode root) {
        if (root == null)
            return true;
        Vector queue = new Vector();
        int level = 1, minLevel = Integer.MAX_VALUE, maxLevel = Integer.MIN_VALUE;
        queue.add(root);
        while (!queue.isEmpty()) {
            int elementCount = queue.size();
            while (elementCount > 0) {
                TreeNode node = queue.remove(0);
                if (isLeaf(node)) {
                    if (minLevel > level)
                        minLevel = level;
                    if (maxLevel < level)
                        maxLevel = level;
                } else {
                    if (node.left != null)
                        queue.add(node.left);
                    if (node.right != null)
                        queue.add(node.right);
                }
                elementCount--;
            }
            if (abs(maxLevel - minLevel) > 1) {
                return false;
            }
            level++;
        }
    
        return true;
    }
    

提交回复
热议问题