250. 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.

Solution:遞歸 post-order 分治 upwards上傳

思路:
Divide: left sub and right sub
Conquer: ifSame(boolean left, boolean right), int count, and then uploads
Time Complexity:T(N) = 2T(N / 2) + O(1) => O(N)
Space Complexity: O(N)

Solution Code:

public class Solution {
    public int countUnivalSubtrees(TreeNode root) {
        int[] count = new int[1];
        helper(root, count);
        return count[0];
    }
    
    private boolean helper(TreeNode node, int[] count) {
        if (node == null) return true;

        // divide
        boolean left = helper(node.left, count);
        boolean right = helper(node.right, count);
        
        // conquer (ifSame(boolean left, boolean right), int count), 
        // and uploads ifSame & count 
        if (left && right) {
            if (node.left != null && node.val != node.left.val) {
                return false;
            }
            if (node.right != null && node.val != node.right.val) {
                return false;
            }
            count[0]++;
            return true;
        }
        return false;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,771評論 0 33
  • Given a binary tree, count the number of uni-value subtre...
    Jeanz閱讀 778評論 0 0
  • 那些死板的老古董就是應該被集體調走。”李亦豆穿著充滿“太陽的味道”的籃球服坐在林伊童的桌子上發表著長篇大論。...
    藍莓林閱讀 312評論 2 2
  • 若是問我原名 不敢再稱流星 怕驚擾靜謐的夜色 怕聽到塵土的笑聲 怕引來天上的故友 賣了同情 再連忙否定 就叫我仆人...
    周牙閱讀 146評論 0 1
  • 一恍神,九月 已過去,9月狀態不算太好,失眠,特別是后面2個星期每天1-2點才睡,于是也沒法早起了?;仡櫿麄€九月,...
    trista_chow閱讀 221評論 0 0