算法-树-平衡二叉树

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

方法二 自底向上

在这里插入图片描述

class Solution {
    
    
    public boolean isBalanced(TreeNode root) {
    
    
        return height(root) >= 0;
    }

    public int height(TreeNode root) {
    
    
        if (root == null) {
    
    
            return 0;
        }
        int leftHeight = height(root.left);
        int rightHeight = height(root.right);
        if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
    
    
            return -1;
        } else {
    
    
            return Math.max(leftHeight, rightHeight) + 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;
 *     }
 * }
 */
class Solution {
    
    
    public boolean isBalanced(TreeNode root) {
    
    
        if(root == null) {
    
    
            return true;
        }
		//先判断当前节点  然后判断左右节点
        return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }


    public int help(TreeNode root) {
    
    
        if(root == null) {
    
    
            return 0;
        }

        int left = height(root.left);
        int right = height(root.right);

        return Math.max(left, right) + 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;
 *     }
 * }
 */
class Solution {
    
    
    public boolean isBalanced(TreeNode root) {
    
    
        if(root == null) {
    
    
            return true;
        }
		//判断当前节点时,先判断左右节点
        return isBalanced(root.left) && isBalanced(root.right) && Math.abs(help(root.left) - help(root.right)) <= 1;
    }


    public int help(TreeNode root) {
    
    
        if(root == null) {
    
    
            return 0;
        }

        int left = help(root.left);
        int right = help(root.right);

        return Math.max(left, right) + 1;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45100361/article/details/113482615