Sword refers to Offer-36-balanced binary tree

Title description

Enter a binary tree to determine whether the binary tree is a balanced binary tree.

Here, we only need to consider its balance, not whether it is a sorted binary tree

Idea analysis

What is a balanced binary tree? A
balanced binary tree is also called an AVL tree (different from the AVL algorithm), and has the following properties: it is an empty tree or the absolute value of the height difference between its left and right subtrees No more than 1, and the left and right subtrees are both a balanced binary tree. This solution is a good solution to the problem of the binary search tree degenerating into a linked list, and the time complexity of insertion, search, and deletion is maintained at O(logN) in the best case and worst case. However, frequent rotation will sacrifice about O(logN) time for insertion and deletion, but compared to binary search trees, the time is much more stable.
Balanced binary tree evolved from searching binary tree (also called sorting binary tree). But this question is not considered.

First of all, the left and right subtrees of the binary tree must also be a binary balanced tree, so the binary tree can be decomposed in a recursive manner. At the same time, the depth difference between the left and right subtrees of the binary tree does not exceed 1. Therefore, the depth is directly calculated and then judged according to the difference in depth.

Code

public class Solution {
    
    
    public boolean IsBalanced_Solution(TreeNode root) {
    
    
        if(root == null) return true;
        if(Math.abs(TreeDeth(root.right)-TreeDeth(root.left))>1){
    
    
            //如果两者的深度差超过了1,说明不平衡
            return false;
        }
        //平衡树的左右子树也应该是平衡树
        return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
        
    }
    /**
    **求二叉树的深度
    **/
    public int TreeDeth(TreeNode root){
    
    
        if(root == null){
    
    
            return 0;
        }
        if(root.left == null&&root.right ==null){
    
    
            return 1;
        }
        return 1+Math.max(TreeDeth(root.right),TreeDeth(root.left));
    }
}

Guess you like

Origin blog.csdn.net/H1517043456/article/details/107434679