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

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

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:
/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public class UniValueCount {        int value;        boolean isUniValue;        int count;        public UniValueCount(int v, boolean is, int num){            value = v;            isUniValue = is;            count = num;        }    }    public int countUnivalSubtrees(TreeNode root) {        UniValueCount res = countUnivalRecur(root);        return res.count;    }        public UniValueCount countUnivalRecur(TreeNode cur){        if (cur==null){            return new UniValueCount(0,false,0);        }        if (cur.left==null && cur.right==null){            return new UniValueCount(cur.val,true,1);        }                UniValueCount res = new UniValueCount(0,true,0);        if (cur.left!=null){            UniValueCount leftRes = countUnivalRecur(cur.left);            res.isUniValue = res.isUniValue && (leftRes.isUniValue && cur.val==leftRes.value);            res.count += leftRes.count;        }        if (cur.right!=null){            UniValueCount rightRes = countUnivalRecur(cur.right);            res.isUniValue = res.isUniValue && (rightRes.isUniValue && cur.val==rightRes.value);            res.count += rightRes.count;        }        if (res.isUniValue){            res.count++;            res.value = cur.val;        }        return res;    }}

 

 
 

 

转载于:https://www.cnblogs.com/lishiblog/p/5874160.html

你可能感兴趣的文章
【概率】poj 2096:Collecting Bugs
查看>>
javascript 无限分类
查看>>
【自制插件】MMD4Maya
查看>>
解决linux服务器乱码
查看>>
mapbox.gl文字标注算法基本介绍
查看>>
【C++】异常简述(二):C++的异常处理机制
查看>>
web.config在哪里
查看>>
SQL Server 2000 版本支持的最大物理内存量
查看>>
spring IOC装配Bean(注解方式)
查看>>
[面试算法题]有序列表删除节点-leetcode学习之旅(4)
查看>>
SpringBoot系列五:SpringBoot错误处理(数据验证、处理错误页、全局异常)
查看>>
kubernetes_book
查看>>
Redis 常用数据结构命令
查看>>
软件工程课堂作业
查看>>
OpenFire 的安装和配置
查看>>
web.config详解
查看>>
ZJOI2018游记Round1
查看>>
侧边栏广告和回到顶部
查看>>
https://blog.csdn.net/u012106306/article/details/80760744
查看>>
【转】从头到尾彻底理解KMP
查看>>