Sword Finger Offer55-II Problem Solution-Balanced Binary Tree

Problem Description

Enter the root node of a binary tree to determine whether the tree is a balanced binary tree. If the difference in depth between the left and right subtrees of any node in a binary tree does not exceed 1, then it is a balanced binary tree.

Example 1:

给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7
返回 true

Example 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4
返回 false

limit:

0 <= 树的结点个数 <= 10000

Problem-solving ideas: post-order traversal + pruning (from bottom to top)

The idea is to do a post-order traversal of the binary tree and return the depth of the subtree from bottom to top. If it is determined that a certain subtree is not a balanced tree, it will "prune" and return directly upwards.

Algorithm flow:
recur(TreeNode p) function

Return value:
When the absolute value of the depth difference between the left and right subtrees of the node root is less than or equal to 1, the depth of the current subtree is returned, that is, the maximum depth of the left/right subtrees of the node root+1 (max(left, right) + 1);
when the absolute value of the depth difference of the left/right subtree of the node root >=2: return −1, which means that this subtree is not a balanced tree.
Termination condition:
when root is empty: it means that the leaf node is crossed, so the height is 0;
when the depth of the left (right) subtree is −1: the left (right) subtree of this tree is not a balanced tree, so pruning, return directly −1;

class Solution {
    
    
    public boolean isBalanced(TreeNode root) {
    
    
        //返回-1表示不是平衡二叉树
        if(recur(root)==-1){
    
    
            return false;
        }else{
    
    
            return true;
        }
    }
    public int recur(TreeNode p){
    
    
        //如果该子树为空,直接返回0
        if(p==null){
    
    
            return 0;
        }
        int leftheight=recur(p.left);       //计算左子树的深度
        int rightheight=recur(p.right);     //计算右子树的深度
        //如果左右子树有一个为-1(代表不平衡)或者左右子树的高度差的绝对值大于1,返回-1
        if(leftheight==-1 || rightheight==-1 || Math.abs(rightheight-leftheight)>1){
    
    
            return -1;
        }else{
    
    
        //否则,返回左右子树的最大值+1
            return Math.max(leftheight,rightheight)+1;
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_39736597/article/details/115030145