Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.
If the tree has more than one mode, return them in any order.
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to the node's key.
The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Input: root = [1,null,2,2]
Output: [2]
Example 2:
Input: root = [0]
Output: [0]
Constraints:
The number of nodes in the tree is in the range [1, 104].
-105 <= Node.val <= 105
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
Solutions
Solution 1
Thinking
The mode is the value with the highest frequency. Hashing every node is \(O(n)\) time and space and fits \(n \le 10^4\), but ignores that the tree is a BST.
Inorder yields a non-decreasing sequence, so equal values are adjacent. Track the predecessor, the current run length, and the best frequency: replace the answer when the run grows, append when it ties. One inorder pass collects every mode with \(O(h)\) extra space.
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcfindMode(root*TreeNode)[]int{mx,cnt:=0,0varprev*TreeNodevarans[]intvardfsfunc(root*TreeNode)dfs=func(root*TreeNode){ifroot==nil{return}dfs(root.Left)ifprev!=nil&&prev.Val==root.Val{cnt++}else{cnt=1}ifcnt>mx{ans=[]int{root.Val}mx=cnt}elseifcnt==mx{ans=append(ans,root.Val)}prev=rootdfs(root.Right)}dfs(root)returnans}
The mode is the value with the highest frequency. Hashing every node fits \(n \le 10^4\) in time, but ignores that the tree is a BST.
Inorder visits the left child first. A chain of \(10^4\) nodes recurses once per node and overflows the call stack.
Inorder is non-decreasing, so equal values are adjacent. The predecessor, the current run length, and the best frequency are enough; the walk does not need a return value.
An explicit stack performs the inorder walk. On entry it pushes an exit marker and the left child; on exit the run length updates the answer, and then the right child is pushed. A longer run replaces the answer, and a tie appends the value.
An inorder walk of a binary search tree is non-decreasing, so equal values are adjacent. An explicit stack carries that walk together with the previous value, the current run length, and the best frequency. On entry we push an exit marker and the left child. On exit the run grows by one when the value matches its predecessor and otherwise restarts at \(1\). A longer run replaces the answer, a tie appends the value, and then the right child is pushed.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the number of nodes in the binary search tree.
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcfindMode(root*TreeNode)[]int{mx,cnt,prev:=0,0,0has:=falsevarans[]inttypeframestruct{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},frame{node.Left,0})continue}ifhas&&prev==node.Val{cnt++}else{cnt=1}ifcnt>mx{ans=[]int{node.Val}mx=cnt}elseifcnt==mx{ans=append(ans,node.Val)}prev=node.Valhas=truestk=append(stk,frame{node.Right,0})}returnans}