算法题收藏

    技术2022-05-20  32

    1、Given a BST (Binary search Tree) how will you find median in that?   Constraints:   * No extra memory. * Function should be reentrant (No static, global variables allowed.) * Median for even no of nodes will be the average of 2 middle elements and for odd no of terms will be middle element only. * Algorithm should be efficient in terms of complexity. 

     

     

    思路:

       1)中序遍历搜索二叉树得到有序的双向链表

       2)采用快慢指针来寻找链表的中间元素

     

    代码:

    typedef struct node { int data; node * lChild; node * rChild; }myNode; // 二叉搜索树node -> 有序的双向链表pre, pre指向链表中最后一个元素 void BST2DLL(myNode *node, myNode* &pre) { if(NULL == node) { return; } BST2DLL(node->lChild, pre); node->lChild = pre; if(NULL != pre) { pre->rChild = node; } pre = node; BST2DLL(node->rChild, pre); } // 寻找双向链表pNode的中间元素,其中pNode指向链表中的最后一个元素 int FindMid(myNode* pNode) { assert(NULL != pNode); myNode* pFast = NULL; myNode* pSlow = NULL; pFast = pNode; pSlow = pNode; while(NULL != pFast && NULL != pSlow) { if(NULL == pFast->lChild) { return pSlow->data; } else if(NULL == pFast->lChild->lChild) { return (pSlow->data + pSlow->lChild->data) >> 1; } else { pFast = pFast->lChild->lChild; pSlow = pSlow->lChild; } } }

     

     

    参考:http://blog.csdn.net/hhygcy/archive/2009/10/11/4654305.aspx


    最新回复(0)