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 ofeverynode never differ by more than 1.

左右子数最大高度差不能超过1

Solution1:

/**
 * 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 ResultType {
    public bool isBalanced;
    public int maxDepth;
    public ResultType (bool isBalanced,int maxDepth){
        this.isBalanced = isBalanced;
        this.maxDepth = maxDepth;
    }
}
public class Solution {

    public bool IsBalanced(TreeNode root) {

        ResultType res =  helper(root);

        return res.isBalanced;
    }
    public ResultType helper(TreeNode root){

        if (root == null){
            return new ResultType (true,0);
        }

        ResultType left = helper(root.left);
        ResultType right = helper(root.right);

        if (!left.isBalanced || !right.isBalanced){
            return new ResultType(false, -1);
        }

        if (Math.Abs(left.maxDepth - right.maxDepth) > 1){
            return new ResultType(false, -1);
        }
        return new ResultType(true, Math.Max(left.maxDepth,right.maxDepth) + 1);
    } 
}
Solution2
/**
 * 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) {
        return helper(root) !=-1;
    }
    public int helper(TreeNode root) {
        if (root == null){
            return 0;
        }

        int left = helper(root.left);
        int right = helper(root.right);            

        if (left==-1 || right==-1 || Math.Abs(left - right)>1){
            return -1;
        }

        return Math.Max(left,right)+1;
    }
}

results matching ""

    No results matching ""