Balanced Binary Tree

来源:互联网 发布:上海美工刀片批发2011 编辑:程序博客网 时间:2024/05/22 12:51

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isBalanced(TreeNode root) {        return maxDepth(root) != -1;    }    private int maxDepth (TreeNode node) {        if (node == null) {            return 0;        }        int left = maxDepth(node.left);        int right = maxDepth(node.right);        if (left == -1 || right == -1 || Math.abs(left - right) > 1) {            return -1;        }        return Math.max(left, right) + 1;    }}


0 0