[leetcode]110. Balanced Binary Tree

Solution 1:自己写的top-bottom的递归

这样的算法复杂度是O(nlgn)

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

Solution 2: 设置一个类变量,边计算高度,边判断,这样只用遍历一次

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    boolean isBalanced=true;
   
    public boolean isBalanced(TreeNode root) {
        
        int res=height(root);
         return isBalanced;
        
    }
    
    public int height(TreeNode root){
        if(root==null) return 0;
        
        int leftH=height(root.left);
        int rightH=height(root.right);
        if(Math.abs(leftH-rightH)>1) this.isBalanced=false;
        return Math.max(leftH,rightH)+1;
        
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_36869329/article/details/89470539