4ms DP solution


  • 0
    T
    public class Solution {
        public int countUnivalSubtrees(TreeNode root) {
            Map<TreeNode, Boolean> map = new HashMap<>();
            if (root == null) return 0;
            compareToRoot(root, map);
            return helper(root, map);
        }
        
        public int helper(TreeNode root, Map<TreeNode, Boolean> map) {
            if (root == null) return 0;
            if (map.get(root) == true) {
                return 1+helper(root.left, map)+helper(root.right, map);
            } 
            return helper(root.left, map)+helper(root.right, map);
        }
        
        public boolean compareToRoot(TreeNode root, Map<TreeNode, Boolean> map) {
            if (map.containsKey(root)) return map.get(root);
            boolean isEqual;
            if (root.left == null && root.right == null) {
                isEqual = true;
            } else if (root.left == null && root.right != null) {
                boolean right = compareToRoot(root.right, map);
                isEqual = root.right.val == root.val ? right : false;
            } else if (root.left != null && root.right == null) {
                boolean left = compareToRoot(root.left, map);
                isEqual = root.left.val == root.val ? left : false;
            } else {
                boolean left = compareToRoot(root.left, map);
                boolean right = compareToRoot(root.right, map);
                isEqual =  left && right && (root.left.val == root.right.val && root.right.val == root.val);
            }
            map.put(root, isEqual);
            return isEqual;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.