程序媛詹妮弗
终身学习

Given a binary tree, count the number of uni-value subtrees.

A Uni-value subtree means all nodes of the subtree have the same value.

Example :

Input:  root = [5,1,5,5,5,null,5]

              5
             / \
            1   5
           / \   \
          5   5   5

Output: 4

 

题意:

给定一棵二叉树,求所有节点都同值的二叉树。

 

思路:

dfs

 

代码:

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

 

posted on 2018-06-12 07:57  程序媛詹妮弗  阅读(324)  评论(0编辑  收藏  举报