编写函数的实现T ComputeMedian() const
在 O(n) 时间内计算树中的中值。假设该树是 BST,但不一定是平衡的。回想一下,n 个数字的中位数定义如下:如果 n 为奇数,则中位数为 x,使得小于 x 的值的数量等于大于 x 的值的数量。如果 n 是偶数,则小于 x 的值的数量加一等于大于 x 的值的数量。例如,给定数字 8、7、2、5、9,中位数为 7,因为有两个值小于 7,两个值大于 7。如果我们将数字 3 添加到集合中,则中位数变为 5。
这是二叉搜索树节点的类:
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; //ONLY INSERT IS READY TO UPDATE THIS MEMBER DATA
int depth, height;
friend class BST<T>;
};
二叉搜索树类:
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've added this member data.
void DelSingle(BSTNode<T>*& ptr);
void DelDoubleByCopying(BSTNode<T>* node);
void ComputeDepth(BSTNode<T>* node, BSTNode<T>* parent);
void ComputeHeight(BSTNode<T>* node);
void Clear(BSTNode<T>* node);
};
我知道我应该首先计算树的节点,然后进行中序遍历,直到到达第 (n/2) 个节点并返回它。我只是不知道怎么做。
正如您所提到的,首先找到节点数并进行任何遍历是相当容易的:
findNumNodes(node):
if node == null:
return 0
return findNumNodes(node.left) + findNumNodes(node.right) + 1
然后,进行中序遍历,当节点数为 n/2 时中止:
// index is a global variable / class variable, or any other variable that is constant between all calls
index=0
findMedian(node):
if node == null:
return null
cand = findMedian(node.left)
if cand != null:
return cand
if index == n/2:
return node
index = index + 1
return findMedian(node.right)
其思想是,中序遍历以排序的方式处理 BST 中的节点。因此,由于该树是 BST,因此i
您处理的第一个节点是i
按顺序排列第 th 个节点,这当然也适用于i==n/2
,当你找到它时n/2
th 节点,您将其返回。
作为旁注,您可以向 BST 添加功能来查找i
有效地第 th 个元素(O(h)
, where h
是树的高度),使用顺序统计树.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)