成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

[LintCode/LeetCode] Count Univalue Subtrees

luzhuqun / 1931人閱讀

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;
    }
}

文章版權歸作者所有,未經(jīng)允許請勿轉載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉載請注明本文地址:http://systransis.cn/yun/71615.html

相關文章

  • [LintCode/LeetCode] Balanced Binary Tree

    摘要:根據(jù)二叉平衡樹的定義,我們先寫一個求二叉樹最大深度的函數(shù)。在主函數(shù)中,利用比較左右子樹的差值來判斷當前結點的平衡性,如果不滿足則返回。 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

    摘要:先排序,然后用數(shù)組記錄每一位上連續(xù)序列的長度,每次循環(huán)更新最大值存為。 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

    摘要:建立一個長度為的數(shù)組,統(tǒng)計所有個字符在出現(xiàn)的次數(shù),然后減去這些字符在中出現(xiàn)的次數(shù)。否則,循環(huán)結束,說明所有字符在和中出現(xiàn)的次數(shù)一致,返回。 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

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<