01. Find Mode in Binary Search Tree
The problem can be found at the following link: Question Link
My Approach
Define
current_val
,current_count
,max_count
, andmodes
. These will be used to keep track of the current value, its count, the maximum count, and the modes (most frequently occurring values) in the tree.Inside the
findMode
function:Call the
in_order_traversal
function on the root node to initiate the in-order traversal of the binary tree.Return the
modes
vector, which contains the modes found during the traversal.
Define a private helper function,
in_order_traversal(TreeNode* node)
, that performs the in-order traversal of the binary tree:Check if the current node is null (base case). If so, return without further processing.
Recursively traverse the left subtree of the current node by calling
in_order_traversal(node->left)
.
Within the
in_order_traversal
function:Update the
current_count
based on whether the value of the current node matches thecurrent_val
. If it matches, incrementcurrent_count
by 1; otherwise, setcurrent_count
to 1.Check if
current_count
is equal tomax_count
. If it is, add the value of the current node to themodes
vector because it's another mode.If
current_count
is greater thanmax_count
, updatemax_count
tocurrent_count
, and reset themodes
vector to contain only the value of the current node (since it's a new mode).Update the
current_val
to the value of the current node for the next comparison.
After processing the left subtree and the current node, recursively traverse the right subtree of the current node by calling
in_order_traversal(node->right)
.
Time and Auxiliary Space Complexity
Time Complexity:
O(n)
Auxiliary Space Complexity:
O(n)
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the rishabhv12/Daily-Leetcode-Solution repository.
Last updated