[LeetCode] #110 Balanced Binary Tree

#110 Balanced Binary Tree

Question

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.

Thinking

此題即求平衡二元樹(Self-Balancing Binary Search Tree;Height-Balancing Binary Search Tree),也被稱為AVL樹,其每個節點的左子樹與右子樹的高度差(或稱為平衡因子)最多只能等於1

My C# Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public bool IsBalanced(TreeNode root) {
        if (root == null) return true;
        var leftDepth = GetDepth(root.left);
        var rightDepth = GetDepth(root.right);
        var balanceFactor = leftDepth - rightDepth;
        return (balanceFactor == 1 
            || balanceFactor == -1 
            || balanceFactor == 0)
            && IsBalanced(root.left) && IsBalanced(root.right);
    }
    
    private int GetDepth(TreeNode node)
    {
        if (node == null) return 0;
        var leftDepth = GetDepth(node.left) + 1;
        var rightDepth = GetDepth(node.right) + 1;
        return (leftDepth > rightDepth) ? leftDepth : rightDepth;
    }
}

Reference:《大話資料結構》Chapter 08 搜尋