Clean DFS solution


  • 3
    E

    The idea is to use DFS to traverse the tree. During traversal, check every node to see if that node is a univalue node. Here, a univalue node means a subtree with that node the root node is a univalue subtree.

    Java code is as follows:

    public class Solution {
    
    private int count;
    
    public int countUnivalSubtrees(TreeNode root) {
        count = 0;
        dfs(root);
        return count;
    }
    
    private boolean dfs(TreeNode root) {
        if(root==null) return true;
        if(root.left==null && root.right==null) {
            count++;
            return true;
        }
        boolean leftUni = dfs(root.left);
        boolean rightUni = dfs(root.right);
        if(leftUni && rightUni 
            && (root.left==null || root.left.val==root.val) 
            && (root.right==null || root.val==root.right.val) ) {
            count += 1;
            return true;
        }
        return false;
    }
    }

Log in to reply
 

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