平衡二叉树

60 阅读1分钟

LeetCode 110

leetcode-cn.com/problems/ba…

代码如下

/**
 * 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 depthLeft = maxDepth(root.left);
        int depthRight = maxDepth(root.right);
        if (Math.abs(depthLeft - depthRight) <= 1 && isBalanced(root.left) && isBalanced(root.right)) {
            return true;
        } else {
            return false;
        }
    }

    public int maxDepth (TreeNode root) {
        if (root == null) return 0;
        else {
            return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
        }
    }
}