题目:求二叉搜索树的中位数。
二叉搜索树结点定义:
struct BSTNode {
int data;
BSTNode *pLeft;
BSTNode *pRight;
BSTNode() : data(0), pLeft(NULL), pRight(NULL) {}
};
解法一:中序遍历
二叉搜索树的中序遍历结果是有序的,利用这一特点很容易找到中位数。
代码:
int TreeData[100];
void InOrderBST(BSTNode *pRoot, int &count)
{
if (pRoot == NULL)
return;
InOrderBST(pRoot->pLeft, count);
TreeData[count] = pRoot->data;
++count;
InOrderBST(pRoot->pRight, count);
}
int medianInBST(BSTNode *pRoot)
{
if (pRoot == NULL)
return -1;
int count = 0;
InOrderBST(pRoot, count);
if (count & 1 == 1) // 奇数个结点
return TreeData[count/2];
else // 偶数个结点
return (TreeData[(count-1)/2] + TreeData[count/2]) /2;
}
如果题目要求:不能额外申请内存;不允许使用static或global变量,该怎么做呢?
解法二