Given the root of a binary tree, return the number of uni-valuesubtrees.
A uni-value subtree means all nodes of the subtree have the same value.
Example 1:
Input: root = [5,1,5,5,5,null,5]
Output: 4
Example 2:
Input: root = []
Output: 0
Example 3:
Input: root = [5,5,5,5,5,null,5]
Output: 6
Constraints:
The number of the node in the tree will be in the range [0, 1000].
-1000 <= Node.val <= 1000
Solutions
Solution 1
Thinking
A subtree is univalue iff both children are univalue and the root equals those children. One bottom-up walk can count them.
\(dfs\) reports whether the subtree is univalue: if both sides succeed and the (possibly missing) child values equal the root, increment and return true.
1 2 3 4 5 6 7 8 910111213141516171819202122232425
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defcountUnivalSubtrees(self,root:Optional[TreeNode])->int:defdfs(root):ifrootisNone:returnTruel,r=dfs(root.left),dfs(root.right)ifnotlornotr:returnFalsea=root.valifroot.leftisNoneelseroot.left.valb=root.valifroot.rightisNoneelseroot.right.valifa==b==root.val:nonlocalansans+=1returnTruereturnFalseans=0dfs(root)returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funccountUnivalSubtrees(root*TreeNode)(ansint){vardfsfunc(*TreeNode)booldfs=func(root*TreeNode)bool{ifroot==nil{returntrue}l,r:=dfs(root.Left),dfs(root.Right)if!l||!r{returnfalse}ifroot.Left!=nil&&root.Left.Val!=root.Val{returnfalse}ifroot.Right!=nil&&root.Right.Val!=root.Val{returnfalse}ans++returntrue}dfs(root)return}