博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LintCode/LeetCode] Count Univalue Subtrees
阅读量:7012 次
发布时间:2019-06-28

本文共 922 字,大约阅读时间需要 3 分钟。

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

转载地址:http://chqtl.baihongyu.com/

你可能感兴趣的文章
MySQL中创建、删除表和库,添加、删除记录
查看>>
Cloudflare能检测HTTPS并拦截MITMEngine
查看>>
android文件系统system-ramdisk-userdata三者之间的关系
查看>>
Collection has neither generic type or OneToMany.targetEntity()
查看>>
使用webmagic抓取页面并保存为wordpress文件
查看>>
前嗅ForeSpider教程:验证码设置
查看>>
搭建LAMP环境PHP无法解析问题
查看>>
(翻译)Quartz官方教程——第十课:配置,资源使用和SchedulerFactory
查看>>
cobbler无人值守安装CentOS7
查看>>
0-1背包问题理解
查看>>
人眼定位识别
查看>>
自执行函数 闭包
查看>>
[置顶] 我的 Java 后端书架 (2016 年暖冬版)
查看>>
centos7在命令行下安装图形界面
查看>>
Sql 先进先出计算积分
查看>>
OpenCV(iOS)平滑处理(模糊,毛玻璃)(10)
查看>>
1 Java NIO概述-翻译
查看>>
《你必须知道的.NET》读后小结(4)
查看>>
Android 应用内存管理-onTrimMemory,onLowMemory
查看>>
AST语法结构树初学者完整教程
查看>>