码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Count Univalue Subtrees

时间:2016-02-13 06:46:08      阅读:552      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/count-univalue-subtrees/

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.

For example:
Given binary tree,

              5
             /             1   5
           / \             5   5   5

 

return 4.

helper funtion 来返回当前tree 是不是 unitree.

两个终止条件一个不能少,若root == null 返回true. 若root是叶子节点, res[0]++, 返回true.

recursion时left保存左子树是否是unitree, right保存右子树是否是unitree.

若都是检查root的val 和左右是否相等,

若想等, res[0]++, 返回true.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int countUnivalSubtrees(TreeNode root) {
12         int [] res = {0};
13         helper(root, res);
14         return res[0];
15     }
16     
17     private boolean helper(TreeNode root, int [] res){
18         if(root == null){
19             return true;
20         }
21         
22         if(root.left == null && root.right == null){
23             res[0]++;
24             return true;
25         }
26         
27         boolean left = helper(root.left, res);
28         boolean right = helper(root.right, res);
29         if(left && right && (root.left == null || root.left.val == root.val) && (root.right == null || root.right.val == root.val)){
30             res[0]++;
31             return true;
32         }
33         return false;
34     }
35 }

 

LeetCode Count Univalue Subtrees

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5187437.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!