java dfs solution


  • 0
    2
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int countUnivalSubtrees(TreeNode root) {
            int[] i = dfs(root);
            return i[1];
        }
        private int[] dfs(TreeNode t) {
            if (t == null) return new int[]{1, 0, 0};
            int[] l = dfs(t.left);
            int[] r = dfs(t.right);
            if (l[1] == 0) l[2] = t.val;
            if (r[1] == 0) r[2] = t.val;
            if (l[0] == 1 && r[0] == 1 && l[2] == t.val && r[2] == t.val) return new int[]{1, l[1] + r[1] + 1, t.val};
            return new int[]{0, l[1] + r[1], t.val};
        }
    }
    

Log in to reply
 

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