边工作边刷题:70天一遍leetcode: day 76
2024-10-11 16:14:12
Count Univalue Subtrees
要点:检测条件比较有意思:因为可能的情况比较多,只要违反了任意一条就return False,所以可以只考虑False的情况,最后return True。
https://repl.it/CoqQ
- 错误点:这题类似Largest BST Subtree(with all descendants,bottom up方法,or post order),左子树不符合只能invalidate root,但仍然要recurse到右子树,所以不能提前返回,而是要在右子树访问完以后返回。
post-order iteration: 注意必须要用map记录,因为post-order没法从栈中获得当前结点左/右子树的情况,所以只能用map记录
https://repl.it/CopV
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def countUnivalSubtrees(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def helper(root):
isUnival = True
if root.left and (not helper(root.left) or root.val!=root.left.val):
isUnival = False
if root.right and (not helper(root.right) or root.val!=root.right.val):
isUnival = False
if not isUnival:
return False
#print root.val
self.count+=1
return True
self.count=0
if not root: return 0
helper(root)
return self.count
# 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.
# Hide Tags Tree
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def countUnivalSubtrees(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
stk = [root]
umap = {}
pre = None
count = 0
while stk:
cur = stk[-1]
if pre==None or pre.left==cur or pre.right==cur:
if cur.left:
stk.append(cur.left)
elif cur.right:
stk.append(cur.right)
elif cur.left==pre:
if cur.right:
stk.append(cur.right)
else:
stk.pop()
if cur.left and (not umap[cur.left] or cur.left.val!=cur.val):
pre = cur
umap[cur]=False
continue
if cur.right and (not umap[cur.right] or cur.right.val!=cur.val):
pre = cur
umap[cur]=False
continue
umap[cur]=True
count+=1
pre = cur
return count
最新文章
- Microsoft.Office.Interop.Word 创建word
- deep learning 练习 多变量线性回归
- 记一次上传文件到七牛云存储的经历(Plupload &; UEditor)(.net)
- DOM样式操作
- modernizer的意义
- sql 语句 截取字符串的两种方案
- URAL 1779 F - The Great Team 构造
- jQuery中的DOM操作总结
- Python学习之路——初识Python
- cocos2d-x环境的搭建之xcode-本人亲历成功搭建!
- sql存储过程——名称 ****不是有效的标识符
- Java面试题大全
- [经典] 使用Python批量重命名iPhone拍摄的照片-按照拍摄时间重命名
- 用CSS实现加载的动画效果
- JSON数据从MongoDB迁移到MaxCompute最佳实践
- python科学计算
- 硬件工程师必会电路模块之MOS管应用
- django 表单使用
- vs安装体验
- LoadRunner 自动关联、手动关联的帖子
热门文章
- 【NOIP训练】【规律+数论】欧拉函数的应用
- 邻接表c源码(构造邻接矩阵,深度优先遍历,广度优先遍历,最小生成树prim,kruskal算法)
- struts2进阶篇(4)
- 在博客中使用MathJax写数学公式
- 【原创】使用.NET Core 1.0创建一个Self-Contained控制台应用
- 自定义View_2_关于自定义组合View
- jDiameter介绍以及使用
- 浅谈ES6中的Proxy
- How does Web Analytics works under sharePoint 2010
- Android 之 Intent(意图)