LeetCode(110)——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.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.

平衡樹,左右子樹的高度差不超過1

AC:

class Solution {
    private boolean childBalanced = true;
    
    public boolean isBalanced(TreeNode root) {
        helper(root);
        
        return childBalanced;
    }
    
    private int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int leftDepth = helper(root.left);
        
        int rightDepth = helper(root.right);
        
        if (Math.abs(leftDepth - rightDepth) > 1) {
            childBalanced = false;
            return 0;
        }
        
        return Math.max(leftDepth, rightDepth) + 1;
    }
}

平衡二叉樹,每個左右子樹的高度差的絕對值不超過1.所以勢必要求每個左右子樹的高度,然後進行比較。一旦有某個節點不滿足平衡的特性,則整個樹就不滿足了。這種解法可以AC,2ms。但是實際應用中不能這麼寫,會有線程不安全的問題。

還有種比較好的方法,不借助外部變量,同時要讓最外層知道是否有破壞平衡性的節點。因爲要算左右子樹的高度差,高度>=0,所以在求左右子樹高度的時候,如果破壞了平衡性,將高度變成-1返回,上層拿到高度爲-1,就知道肯定是出現了異常,即不平衡。

public boolean isBalanced(TreeNode root) {
        return helper(root) != -1;
    }
    
    private int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int leftDepth = helper(root.left);
        if (leftDepth == -1) {
            return -1;
        }
        
        int rightDepth = helper(root.right);
        if (rightDepth == -1) {
            return -1;
        }
        
        if (Math.abs(leftDepth - rightDepth) > 1) {
           return -1;
        }
        
        return Math.max(leftDepth, rightDepth) + 1;
    }

 

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