Java는 이진 트리가 균형 잡힌 이진 트리인지 여부를 판단합니다.

이진 트리가 균형 이진 트리인지 확인

주제 설명

높이 균형 이진 트리는 다음과 같이 정의됩니다. 이진 트리의 각 노드의 왼쪽 및 오른쪽 하위 트리 높이 차이의 절대값은 1을 초과하지 않습니다.

여기에 이미지 설명 삽입
여기에 이미지 설명 삽입

여기에 이미지 설명 삽입

원제 OJ 링크

https://leetcode.cn/problems/balanced-binary-tree/

답변 코드

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
 import java.lang.Math;
class Solution {
    
    
    public boolean isBalanced(TreeNode root) {
    
    
        if(root == null){
    
    
            return true;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        if((Math.abs(leftH-rightH)<=1) && isBalanced(root.left) && isBalanced(root.right)){
    
    
            return true;
        }
        return false;


    }
    public int getHeight(TreeNode root){
    
    //求树的深度(高度)
        if(root == null){
    
    
            return 0;
        }
        if(root.right == null && root.left == null){
    
    
            return 1;
        }
//        int count1 = getHeight(root.left)+1;
//        int count2 = getHeight(root.right)+1;
//        return Math.max(count1,count2);
        return Math.max(getHeight(root.left)+1, getHeight(root.right)+1);
    }
}

이 코드의 한 가지 단점은 실제로 반복적인 작업을 많이 한다는 것입니다.실제로 이중 계층 재귀를 수행하고 있습니다.각 노드는 왼쪽 및 오른쪽 하위 트리의 높이를 계산합니다.만족되지 않은 차이의 절대 값이 다음보다 작은 경우 또는 1과 같으면 false를 반환하지만 실제로는 높이를 계산할 때 이 작업을 직접 수행할 수 있습니다. return -1. 후속 노드의 높이는 전혀 계산할 필요가 없습니다.
따라서 다음 코드가 있습니다.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
 import java.lang.Math;
class Solution {
    
    
    public boolean isBalanced(TreeNode root) {
    
    
        return maxDepth(root)>=0;
    }
    public int maxDepth(TreeNode root){
    
    
        if(root == null){
    
    
            return 0;
        }
       int count1 = maxDepth(root.left);
       if(count1<0){
    
    
           return-1;
       } 
       int count2 = maxDepth(root.right);
       if(count2<0){
    
    
           return -1;
       }
       if(Math.abs(count1-count2)<=1){
    
    
           return Math.max(count1,count2)+1;
       }
       else{
    
    
           return -1;
       }
    }
}

추천

출처blog.csdn.net/baixian110/article/details/130943838