Write an implementation of the T ComputeMedian() const function, which calculates the median value in the tree in O (n) time. Suppose the tree is BST, but not necessarily balanced. Recall that the median of n numbers is defined as follows: if n is odd, the median is x, so that the number of values less than x is equal to the number of values greater than x. If n is even, then one plus the number of values less than x is equal to the number of values greater than x. For example, given the numbers 8, 7, 2, 5, 9, the median is 7, because there are two values less than 7 and two values greater than 7. If we add the number 3 to the set, the median will become 5.
Here is the node binary search tree class:
template <class T> class BSTNode { public: BSTNode(T& val, BSTNode* left, BSTNode* right); ~BSTNode(); T GetVal(); BSTNode* GetLeft(); BSTNode* GetRight(); private: T val; BSTNode* left; BSTNode* right; BSTNode* parent;
Search tree binary class:
template <class T> class BST { public: BST(); ~BST(); bool Search(T& val); bool Search(T& val, BSTNode<T>* node); void Insert(T& val); bool DeleteNode(T& val); void BFT(void); void PreorderDFT(void); void PreorderDFT(BSTNode<T>* node); void PostorderDFT(BSTNode<T>* node); void InorderDFT(BSTNode<T>* node); void ComputeNodeDepths(void); void ComputeNodeHeights(void); bool IsEmpty(void); void Visit(BSTNode<T>* node); void Clear(void); private: BSTNode<T> *root; int depth; int count; BSTNode<T> *med;
I know that I must first count the nodes of the tree, and then do a roundabout until I get to the (n / 2) th node and return it. I just have no idea.
source share