剑指 Offer 55 - II. 平衡二叉树

时间:2021-04-13 12:05:30   收藏:0   阅读:0

利用上一题求深度的做法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    Boolean res = true;


    public boolean isBalanced(TreeNode root) {
        dfs(root);
        return res;
    }

    int dfs(TreeNode root){
        if(root == null) return 0;
        int left = dfs(root.left);
        int right = dfs(root.right);
        if(Math.abs(left-right) > 1) res = false;
        return Math.max(left, right) + 1;
    }
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!