Clever use of -1

Problem description: http://lintcode.com/en/problem/balanced-binary-tree/#

The use of -1 here is very clever!!!

The reason that we can return - 1 to denote non-balanced binary tree is that the depth must be a positive number. So -1 doesn't represent any depth value.
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
    public boolean isBalanced(TreeNode root) {
        // write your code here
        if(root == null){
            return true;
        }

        return maxDepth(root) != -1;
    }

    public int maxDepth(TreeNode root) {
        // write your code here
        if(root == null){
            return 0;
        }

        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        if(left == -1 || right == -1 || Math.abs(left - right) > 1){
            return -1;
        }

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

results matching ""

    No results matching ""