1.题目描述
给定一个二叉树,统计该二叉树数值相同的子树个数。
同值子树是指该子树的所有节点都拥有相同的数值。
示例:
输入: root = [5,1,5,5,5,null,5]
5
/ \
1 5
/ \ \
5 5 5
2.解题思路
走二叉树的后序遍历判断左右子树的值是否与当前子树根节点值相等,将结果返回给上一层
3.代码实现
# 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 __init__(self):
self.count = 0
def dfs(self, root):
if not root:
return True
l = self.dfs(root.left)
r = self.dfs(root.right)
cur = True
if root.left and root.val != root.left.val:
cur = False
if root.right and root.val != root.right.val:
cur = False
if l and r and cur:
self.count += 1
return l and r and cur
def countUnivalSubtrees(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.dfs(root)
return self.count