My AC Java Code


  • 7
    A
    public class Solution {
        public int countUnivalSubtrees(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int[] counter = new int[1];
            count(root, counter, root.val);
            return counter[0];
        }
        
        private boolean count(TreeNode root, int[] counter, int val) {
            if (root == null) {
                return true;
            }
            boolean l = count(root.left, counter, root.val);
            boolean r = count(root.right, counter, root.val);
        
            if (l && r) {
                counter[0]++;
            }
            
            return l && r && root.val == val;
        }
        
    }

  • 0
    S

    I'm wondering why did you use int[] counter particularly instead of just use an int.


  • 0
    H

    cuz what changes he makes to count[0] inside of count method will still exist after the method returns... an integer is also ok if you make it an instance variable... otherwise it will only be passed by value and nothing will be changed when the method finished


  • 0
    6

    great solution. one question, how do you come up with the idea that the count function returns a boolean value? thanks.


Log in to reply
 

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