LeetCode 题解(265) : Count Univalue Subtrees
来源:互联网 发布:淘宝卖的印度威格拉 编辑:程序博客网 时间:2024/06/04 18:33
题目:
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
.
递归。
Java版:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int countUnivalSubtrees(TreeNode root) { unival(root); return count; } private boolean unival(TreeNode root) { if(root == null) return true; if(root.left ==null && root.right == null) { count++; return true; } boolean left = unival(root.left); boolean right = unival(root.right); if(left && right && (root.left == null || root.left.val == root.val) && (root.right == null || root.right.val == root.val)) { count++; return true; } return false; } private int count = 0;}
Python版:
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def __init__(self): self.count = 0 def countUnivalSubtrees(self, root): """ :type root: TreeNode :rtype: int """ self.unival(root) return self.count def unival(self, root): if root == None: return True if root.left == None and root.right == None: self.count += 1 return True left = self.unival(root.left) right = self.unival(root.right) if left and right and (root.left == None or root.left.val == root.val) and (root.right == None or root.right.val == root.val): self.count += 1 return True else: return False
0 0
- LeetCode 题解(265) : Count Univalue Subtrees
- [LeetCode 265] Count Univalue Subtrees
- Leetcode: Count Univalue Subtrees
- *LeetCode-Count Univalue Subtrees
- Leetcode 250Count Univalue Subtrees
- LeetCode 250. Count Univalue Subtrees
- [leetcode] 250. Count Univalue Subtrees 解题报告
- Leetcode 250. Count Univalue Subtrees (Medium) (cpp)
- [Leetcode] 250. Count Univalue Subtrees 解题报告
- [LeetCode250]Count Univalue Subtrees
- Count Univalue Subtrees
- Count Univalue Subtrees
- 250. Count Univalue Subtrees
- 250. Count Univalue Subtrees
- LeetCode 250. Count Univalue Subtrees(单值子树)
- [leetcode 250]Count Univalue Subtrees ------元素都相同的子树个数
- LeetCode题解:Count Primes
- leetcode 题解 Count Primes
- HDU 1824 Let's go home 2-sat基础
- DIV中class和id的区别
- warning:deprecated conversion from string constant to 'char *' 解决方案
- linux mysql jdk mongodb web
- ARM 初解
- LeetCode 题解(265) : Count Univalue Subtrees
- ActiveMQ简单使用介绍
- hibernate3和spring3集成无法自动建表的原因
- HTML中引入CSS的方法
- [Android UI开发] viewpager fragment 切换时oncreateview调用多次问题
- Java____Javascript思维导图
- 二维面阵FFT波束形成matlab
- HDU1033 Eage(java)
- ETL工具kettle实现循环