判断是否为平衡二叉树 (判断是否为平衡二叉树)

 

思路:

// @Title: 判断是否为平衡二叉树 (判断是否为平衡二叉树)
// @Author: qisiii
// @Date: 2022-03-01 17:29:29
// @Runtime: 1 ms
// @Memory: 40.7 MB
// @comment: 
// @flag: 
/**
 * 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;
    }
    //计算当前子树的差&&左子树是平衡&&右子树是平衡
      boolean current=Math.abs(doHigh(root.left)-doHigh(root.right))<=1;
    return current&&isBalanced(root.left)&&isBalanced(root.right);
    }
    
    public int doHigh(TreeNode root){
        if(root==null){
            return 0;
        }
        if(root.left!=null||root.right!=null){
            return Math.max(doHigh(root.left),doHigh(root.right))+1;
        }
        return 1;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18