构件特殊堆

来源:互联网 发布:大萝卜网络什么意思 编辑:程序博客网 时间:2024/06/04 04:19

http://www.1point3acres.com/bbs/thread-13292-1-1.html

A rooted binary tree with keys in its nodes has the binary search tree
property (BST property) if, for every node, the keys in its left
subtree are smaller than its own key, and the keys in its right
subtree are larger than its own key. It has the heap property if, for
every node, the keys of its children are all smaller than its own key.
You are given a set of n binary tree nodes that each contain an
integer i and an integer j. No two i values are equal and no two j
values are equal. We must assemble the nodes into a single binary tree
where the i values obey the BST property and the j values obey the
heap property. If you pay attention only to the second key in each
node, the tree looks like a heap, and if you pay attention only to the
first key in each node, it looks like a binary search tree.Describe a
recursive algorithm for assembling such a tree


和以前的一个根据中序和前续遍历构建二叉树的题目一样的解法:struct TREE_NODE {        int nLVal;        int nRVal;        TREE_NODE* pLft;        TREE_NODE* pRgt;};bool SortLftVal(const TREE_NODE& node1, const TREE_NODE& node2){        return node1.nLVal < node2.nLVal;}//Already sorted by the first valueTREE_NODE* _inner_construct(TREE_NODE nodes[], int n){        assert(nodes);        if (0 == n) return NULL;        //find the corresponding index of node with second value the biggest        int nIndex = 0;        for (int i = 0; i < n; i++)        {                if (nodes[i].nRVal > nodes[nIndex].nRVal)                        nIndex = i;        }        nodes[nIndex].pLft = _inner_construct(nodes, nIndex);        nodes[nIndex].pRgt = _inner_construct(nodes+nIndex+1, n-nIndex-1);        return &nodes[nIndex];}TREE_NODE* ConstructBSTHeapTree(TREE_NODE nodes[], int n){        assert(nodes && n>0);        sort(nodes, nodes+n, SortLftVal);        return _inner_construct(nodes, n);}

每次在一个片段上寻找最大元素的时候,可以用RMQ实现


原创粉丝点击