[leetcode]Balanced Binary Tree - java 递归

/**

 * Definition for binary tree

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode(int x) { val = x; }

 * }

 */

public class Solution {

    public boolean isBalanced(TreeNode root) {

        int b = b(root);

        if(b==-1){

            return false;

        }

        return true;

    }



    public int b(TreeNode node){

        if(node==null){

            return 0;

        }

        int lb = b(node.left);

        int rb = b(node.right);

        if(lb==-1 || rb==-1 || Math.abs(lb-rb)>1){

            return -1;

        }

        return 1+Math.max(lb,rb);

    }

}

 

你可能感兴趣的:(LeetCode)