[Note details] Java implementation of "Sword Finger Offer": Input a binary tree to determine whether the binary tree is a balanced binary tree.

1. 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

The Balanced Binary Tree has the following properties: it is an empty tree or the absolute value of the height difference between its left and right subtrees does not exceed 1, and the left and right subtrees are both a balanced binary tree.

First of all, what is a balanced binary tree?

    ① It can be an empty tree

    ② If it is not an empty tree, the left and right subtrees of any node are balanced binary trees, and the absolute value of the difference in height does not exceed 1.

For example, the following is a balanced binary tree.

    

2. Algorithm analysis

     ① The key to judging a balanced binary tree is to find the height difference of the binary tree. The height difference between left and right children of any node cannot exceed 1.

     ② The subject of this question requires the height of the binary tree, and then the left subtree and the right subtree are the difference

3. Code implementation

public class Solution {
  // 设置一个布尔类型的值
    boolean flag = true;
    public boolean IsBalanced_Solution(TreeNode root) {
        treeHeight(root);
        // 通过flag的true 或者是false 来判断该树是否是平衡二叉树
        return flag;
    }
  
    // 求树的高度
    public int treeHeight(TreeNode root){
       if(root == null){
         return 0;
       }
       int left = treeHeight(root.left);
       int right = treeHeight(root.right);
       // 判断二叉树是否是平衡二叉树的条件
       // 当前的条件不是平衡二叉树
       if((left - right) > 1 || (right - left) > 1){
          flag = false;
          return -1;
       }
       // 判断完成,返回树的高度, 最后一个 left + 1;right+1是算上根节点的
       return left>right?(left+1):(right+1);
    }
}

 

 

 

Guess you like

Origin blog.csdn.net/Sunshineoe/article/details/115016239