leetcode -- Balanced Binary Tree

Balanced Binary Treenode

Given a binary tree, determine if it is height-balanced.this

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.code

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

        if(root==null){
            return 0;
        }
        int ldep = maxDepth(root.left);
        int rdep = maxDepth(root.right);
        return ldep> rdep? ldep+1: rdep +1;

    }
    
    public boolean isBalanced(TreeNode root) {
        if (root==null){
            return true;
        }

        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        int diff = left - right;

        if(diff > 1 || diff <-1){
            return false;
        }

        return isBalanced(root.left) && isBalanced(root.right);
    }
}
相關文章
相關標籤/搜索