LeetCode不定時刷題——Balanced Binary Tree

Balanced Binary Tree

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

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.

/**
 * 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;
        }
       return height(root)!=-1;
    }
    public int height(TreeNode root){
        if(root==null){
        return 0;
        }    
        int sum1=height(root.left);
        int sum2=height(root.right);
        if(sum1==-1||sum2==-1||Math.abs(sum1-sum2)>1){
            return -1;
        }
        else if(sum1-sum2>0){
        return sum1+1;
        }
        else return sum2+1;
    }
}

用遞歸來做,判斷左右字數深度是否大於1,大於1就返回-1,然後往上的節點也不需要比較直接置-1即可,否則就不斷給深度大

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章