Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.
The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).
Example 1:
Input: root = [5,2,-3]
Output: [2,-3,4]
Example 2:
Input: root = [5,2,-5]
Output: [2]
Constraints:
The number of nodes in the tree is in the range [1, 104].
-105 <= Node.val <= 105
Solutions
Solution 1: Hash Table + DFS
Thinking
A subtree sum is left + right + root, so both children must be known first. Rescanning each subtree repeats work.
A post-order DFS returns the current sum and a hash map counts frequencies. After the walk, keep the sums whose frequency is maximal. One traversal both sums and counts.
We can use a hash table \(\textit{cnt}\) to record the frequency of each subtree sum. Then, we use depth-first search (DFS) to traverse the entire tree, calculate the sum of elements for each subtree, and update \(\textit{cnt}\).
Finally, we traverse \(\textit{cnt}\) to find all subtree sums that appear most frequently.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the number of nodes in the binary tree.
1 2 3 4 5 6 7 8 91011121314151617181920
# 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:deffindFrequentTreeSum(self,root:Optional[TreeNode])->List[int]:defdfs(root:Optional[TreeNode])->int:ifrootisNone:return0l,r=dfs(root.left),dfs(root.right)s=l+r+root.valcnt[s]+=1returnscnt=Counter()dfs(root)mx=max(cnt.values())return[kfork,vincnt.items()ifv==mx]
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcfindFrequentTreeSum(root*TreeNode)(ans[]int){cnt:=map[int]int{}varmxintvardfsfunc(*TreeNode)intdfs=func(root*TreeNode)int{ifroot==nil{return0}s:=root.Val+dfs(root.Left)+dfs(root.Right)cnt[s]++mx=max(mx,cnt[s])returns}dfs(root)fork,v:=rangecnt{ifv==mx{ans=append(ans,k)}}return}
A subtree sum is the left sum plus the right sum plus the node value, so both children must be known first. Rescanning each subtree repeats work. Returning the sum from a postorder recursion is correct on a short tree.
The tree can contain \(10^4\) nodes. A left chain makes this postorder walk recurse once per node and overflow the call stack.
Each sum depends only on the two children, so children must be finished before their parent. Frequencies can be counted in a hash table during the walk.
An explicit stack performs that postorder walk. On entry it pushes an exit marker and the two children; on exit it writes the subtree sum into the hash table. After the walk, the sums with the highest frequency are the answer.
A hash table \(\textit{cnt}\) records how often each subtree sum appears. An explicit stack walks the binary tree in postorder. On entry we push an exit marker, then the right child and the left child. On exit the children's sums are already stored, the current sum is those two plus the node value, and \(\textit{cnt}\) is updated.
Finally we keep every subtree sum whose frequency is maximal.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the number of nodes in the binary tree.
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcfindFrequentTreeSum(root*TreeNode)(ans[]int){cnt:=map[int]int{}sub:=map[*TreeNode]int{}mx:=0typeframestruct{node*TreeNodestateint}stk:=[]frame{{root,0}}forlen(stk)>0{cur:=stk[len(stk)-1]stk=stk[:len(stk)-1]node,state:=cur.node,cur.stateifnode==nil{continue}ifstate==0{stk=append(stk,frame{node,1})ifnode.Right!=nil{stk=append(stk,frame{node.Right,0})}ifnode.Left!=nil{stk=append(stk,frame{node.Left,0})}continue}l,r:=0,0ifnode.Left!=nil{l=sub[node.Left]}ifnode.Right!=nil{r=sub[node.Right]}s:=node.Val+l+rcnt[s]++mx=max(mx,cnt[s])sub[node]=s}fork,v:=rangecnt{ifv==mx{ans=append(ans,k)}}return}