平衡二叉树

平衡树:对于每一个节点它的左右子树深度差不能超过1

/**
 * 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;
        return (Math.abs(getDepth(root.left)-getDepth(root.right))<=1)
                && isBalanced(root.left) && isBalanced(root.right);//递归判断每个节点的子数深度
    }
    public int getDepth(TreeNode root){//求深度
        if(root == null) return 0;
        return Math.max(getDepth(root.left),getDepth(root.right))+1;

    }
}

代码参考:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/solution/cjian-ji-dai-ma-ji-hu-shuang-bai-di-gui-2xing-by-o/

posted @ 2020-07-23 19:12  浅滩浅  阅读(102)  评论(0编辑  收藏  举报