yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #250. Count Univalue Subtrees #230

Open yokostan opened 5 years ago

yokostan commented 5 years ago

'Brute Force' verbose version:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Pair {
    public boolean isUnival;
    public int count;

    public Pair(boolean isUnival, int count) {
        this.isUnival = isUnival;
        this.count = count;
    }
}

class Solution {
    public int countUnivalSubtrees(TreeNode root) {
        return univalSubtreeCount(root).count;
    }

    private Pair univalSubtreeCount(TreeNode root) {
        if (root == null) {
            return new Pair(true, 0);
        }

        if (root.left == null && root.right == null) {
            return new Pair(true, 1);
        }

        Pair left = univalSubtreeCount(root.left);
        Pair right = univalSubtreeCount(root.right);

        //an important step to check whether left and right subtrees are all valid
        if (left.isUnival && right.isUnival) {
            if (root.left == null && root.val == root.right.val) {
                return new Pair(true, left.count + right.count + 1);
            }
            if (root.right == null && root.val == root.left.val) {
                return new Pair(true, left.count + right.count + 1);
            }
            if (root.left != null && root.right != null && root.val == root.left.val && root.val == root.right.val) {
                return new Pair(true, left.count + right.count + 1);
            }
        }

        return new Pair(false, left.count + right.count);
    }
}

For this problem, the most important thing is that we need both isValid boolean value and int count value, so we can either set a count[] array and pass in the helper function or set count to be global variable.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int count = 0;
    public int countUnivalSubtrees(TreeNode root) {
        helper(root);
        return count;
    }

    private boolean helper(TreeNode root) {
        if (root == null) return true;
        boolean left = helper(root.left);
        boolean right = helper(root.right);

        if (left && right) {
            if (root.left != null && root.val != root.left.val) return false;
            if (root.right != null && root.val != root.right.val) return false;
            count++;
            return true;
        }

        return false;
    }
}