LeetCode Algorithm Recursive Class - Balanced Binary Tree

Table of contents

110. Balanced Binary Tree

answer:

operation result:

Optimized version 1:

operation result:


Given a binary tree, determine whether it is a height-balanced binary tree.

In this question, a height balanced binary tree is defined as:

The absolute value of the height difference between the left and right subtrees  of each node in a binary tree does not exceed 1.

Example 1:

Input: root = [3,9,20,null,null,15,7]
 Output: true

Example 2:

Input: root = [1,2,2,3,3,null,null,4,4]
 Output: false

Example 3:

Input: root = []
 Output: true

hint:

  • The number of nodes in the tree is in the  [0, 5000] range
  • -104 <= Node.val <= 104

题解:

The idea is in 104. The maximum depth of the binary tree - LeetCode

Completed on the idea, the corresponding problem solution is LeetCode algorithm recursive class - the maximum depth of the binary tree_turbo summer Soseki's blog-CSDN blog

  1. Define a function deep to calculate the depth and a global variable res of Boolean type to save the result
  2. Call the deep function to calculate the depth
  3. The deep function recursively calculates the depth of each layer and compares the depths of the left and right subtrees
  4. If it is greater than one, modify the res value to false

代码:

class Solution {
    boolean res=true;
    public boolean isBalanced(TreeNode root) {
        deep(root);
        return res;
    }
    private int deep(TreeNode root){
        if(root==null) return 0;
        int left=deep(root.left);
        int right=deep(root.right);
        if(Math.abs(left-right)>1){
           res=false;
        }
        return Math.max(left,right)+1;
    }
}

operation result:

 

Optimized version 1:

class Solution {
    boolean res=true;
    public boolean isBalanced(TreeNode root) {
        deep(root);
        return res;
    }
    private int deep(TreeNode root){
        if(root==null) return 0;
        int left=deep(root.left);
        int right=deep(root.right);
        if(Math.abs(left-right)>1){
           res=false;
           return -1;
        }
        return Math.max(left,right)+1;
    }
}

The difference between the modified method 2 and method 1 is that -1 is returned directly when an imbalance is found, instead of modifying the global variable res and terminating the calculation. Doing so terminates the computation early, avoiding unnecessary recursive calls, and thus potentially determining the result sooner.

operation result:

 

Guess you like

Origin blog.csdn.net/qq_62799214/article/details/132273942