LeetCode - 110. Balenced Binary Tree(Tree, DFS, BFS, Recursion)*

YAMAMAMO·2022년 11월 3일
0

LeetCode

목록 보기
78/100

문제

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

https://leetcode.com/problems/balanced-binary-tree/

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: true

Example 2:

Input: root = [1,2,2,3,3,null,null,4,4]
Output: false

Example 3:

Input: root = []
Output: true

풀이

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null) return true;
        return maxDepth(root,1)!=-1;
    }
    public int maxDepth(TreeNode root, int dep){
        if(root==null) return dep;
        
        int left = maxDepth(root.left, dep);
        int right = maxDepth(root.right, dep);
        
        if(left==-1||right==-1||Math.abs(left-right)>1) return -1;
        
        return Math.max(left,right)+1;
    }
}
profile
안드로이드 개발자

0개의 댓글