构件特殊堆

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 value
TREE_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实现


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值