zoukankan      html  css  js  c++  java
  • [LC] 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.

    Example :

    Input:  root = [5,1,5,5,5,null,5]
    
                  5
                 / 
                1   5
               /    
              5   5   5
    
    Output: 4

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        int res = 0;
        public int countUnivalSubtrees(TreeNode root) {
            helper(root);
            return res;
        }
        
        private boolean helper(TreeNode root) {
            if (root == null) {
                return true;
            }
            boolean left = helper(root.left);
            boolean right = helper(root.right);
            if (left && right) {
                if (root.left != null && root.left.val != root.val) {
                    return false;
                }
                if (root.right != null && root.right.val != root.val) {
                    return false;
                }
                res += 1;
                return true;
            }
            
            /** another way
            if (left && right && 
               (root.left == null || root.val == root.left.val) && 
               (root.right == null || root.val == root.right.val)) {
                res++;
                return true;
            }
            */
            return false;
        }
    }
  • 相关阅读:
    windows禅道环境搭建
    python-django开发学习笔记四
    迭代器
    小数据池
    正则表达式
    文件操作
    深浅拷贝
    隐藏文件夹命令
    python解释器安装教程以及环境变量配置
    计算机基础应用
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12191184.html
Copyright © 2011-2022 走看看