天天看點

劍指offer(牛客)---38.平衡二叉樹

題目描述

輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
         return getDepth(root) != -1;
    }
     private int getDepth(TreeNode root) {
        if (root == null) return 0;
        int left = getDepth(root.left);
        if (left == -1) return -1;
        int right = getDepth(root.right);
        if (right == -1) return -1;
        return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(left, right);
    }
}
           

從根結點開始,左右節點兩邊周遊,然後相減,如果出現不等于0說明該子樹不平衡,就直接傳回-1,相當于整棵樹就不是平衡樹;

繼續閱讀