剑指OFFER----面试题55 - II. 平衡二叉树

链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean ans = true; 
    public boolean isBalanced(TreeNode root) {
        dfs(root);
        return ans;
    }

    public int dfs(TreeNode root) {
        if (root == null) return 0;
        int left = dfs(root.left), right = dfs(root.right);
        if (Math.abs(left - right) > 1) ans = false;
        return Math.max(left, right) + 1;
    }
}
posted @ 2020-03-10 13:14  景云ⁿ  阅读(54)  评论(0编辑  收藏  举报