zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    git 分支建立及合并
    git push 冲突
    Ubuntu 16.04下安装64位谷歌Chrome浏览器
    Nginx+uswgi+Django部署
    Deepin下python安装uwsgi报错: Python.h:没有那个文件或目录
    Deepin系统更新apt-get源
    语义化的理解
    尝试Vue3.0
    Vue3.0响应式实现
    Vue2.0响应式原理以及重写数组方法
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5065467.html
Copyright © 2011-2022 走看看