leetcode 250 Count Univalue Subtrees

 

The idea is very simple, there is an optimal sub-structure, from top to bottom solution can recursively.

How to determine the current root tree represents whether the uni-value subtree?

1. Check root and left, right value consistent

Whether 2. left subtree and right subtree are uni-value

Note that the second step may be left, right is empty, if you want to pay attention to when writing

 1 class Solution {  
 2     private int count;
 3     public int countUnivalSubtrees(TreeNode root) {  
 4         uni(root);  
 5         return count;  
 6     }  
 7       
 8     boolean uni(TreeNode root) {  
 9         if(root == null)  
10             return true;  
11         if(root.left ==null && root.right == null) {  
12             count++;  
13             return true;  
14         }  
15         bool left = uni(root.left);  
16         bool right = uni(root.right);  
17         if(left && right && (root.left == null || root.left.val == root.val) && (root.right == null || root.right.val == root.val)) {  
18             count++;  
19             return true;  
20         }  
21         return false;  
22     }  
23 }

 

Guess you like

Origin www.cnblogs.com/hwd9654/p/11361422.html