资讯专栏INFORMATION COLUMN

[LintCode/LeetCode] Count Univalue Subtrees

luzhuqun / 1798人阅读

Problem

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

Given root = {5,1,5,5,5,#,5}, return 4.

          5
         / 
        1   5
       /    
      5   5   5
     
Solution
public class Solution {
    /**
     * @param root: the given tree
     * @return: the number of uni-value subtrees.
     */
    private int count = 0;
    public int countUnivalSubtrees(TreeNode root) {
        // write your code here
        helper(root, 0);
        return count;
    }

    private boolean helper(TreeNode root, int value) {
        if (root == null) return true;
        // we need the root.val as the reference in the recursion
        boolean left = helper(root.left, root.val);
        boolean right = helper(root.right, root.val);
        if (left && right) {
            count++;
            return root.val == value;
        }
        
        return false;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/71615.html

相关文章

  • [LintCode/LeetCode] Balanced Binary Tree

    摘要:根据二叉平衡树的定义,我们先写一个求二叉树最大深度的函数。在主函数中,利用比较左右子树的差值来判断当前结点的平衡性,如果不满足则返回。 Problem Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as...

    morgan 评论0 收藏0
  • [LintCode/LeetCode] Longest Consecutive Sequence

    摘要:先排序,然后用数组记录每一位上连续序列的长度,每次循环更新最大值存为。 Problem Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Clarification Your algorithm should run in O(n) com...

    buildupchao 评论0 收藏0
  • [LintCode/LeetCode] Count Binary Substrings

    Problem Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0s and 1s, and all the 0s and all the 1s in these substrings are grouped consecutively. Subs...

    BaronZhang 评论0 收藏0
  • [LintCode/LeetCode] Integer Replacement

    Problem Given a positive integer n and you can do operations as follow: 1.If n is even, replace n with n/2.2.If n is odd, you can replace n with either n + 1 or n - 1. What is the minimum number of re...

    fyber 评论0 收藏0
  • [LintCode/LeetCode] Two Strings are Anagrams/Valid

    摘要:建立一个长度为的数组,统计所有个字符在出现的次数,然后减去这些字符在中出现的次数。否则,循环结束,说明所有字符在和中出现的次数一致,返回。 Program Write a method anagram(s,t) to decide if two strings are anagrams or not. Example Given s=abcd, t=dcab, return true....

    vslam 评论0 收藏0

发表评论

0条评论

luzhuqun

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<