• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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.

The condition for a subtree to be a uni-value subtree is that:

(The left subtree has to be a uni-value subtree or null) && (right subtree has to be a uni-value subtree or null) && (left null || left.val== root.val) && (right null || right.val==root.val)

 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         if (root == null) return 0;
13         ArrayList<Integer> sum = new ArrayList<Integer>();
14         sum.add(0);
15         helper(root, sum);
16         return sum.get(0);
17     }
18     
19     public boolean helper(TreeNode root, ArrayList<Integer> sum) {
20         if (root == null) return true;
21         boolean left = helper(root.left, sum);
22         boolean right = helper(root.right, sum);
23         if (left && right && (root.left==null || root.val==root.left.val) && (root.right==null || root.val==root.right.val)) {
24             sum.set(0, sum.get(0)+1);
25             return true;
26         }
27         return false;
28     }
29 }

 

posted @ 2015-12-22 07:22  neverlandly  阅读(1747)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3