何海涛100题(1)自己心得

原题在这里:

http://zhedahht.blog.163.com/blog/static/254111742007127104759245/

自己的总结:

为了将一个二叉查找树转变为双向链表,在递归将左子树右子树都变成双向链表后,需要将左子树中的最大元素和当前元素串联起来(右子树中的最小元素同理),对于这一操作,我们不可以先进入子树中再操作,因为从当前节点访问子节点(both左右)都很容易(有指针,直接访问就好),但是从子节点访问父亲节点没法直接访问(无指针,无法直接访问)。

#include <iostream>
using namespace std;


struct BSTreeNode // a node in the binary search tree
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};

BSTreeNode
* ConvertNode(BSTreeNode* pNode, bool asRight);

int main()
{
BSTreeNode node1, node2, node3;
node1.m_nValue
= 2;
node2.m_nValue
= 1;
node3.m_nValue
= 3;
node1.m_pLeft
= &node2;
node1.m_pRight
= &node3;
node2.m_pLeft
= 0;
node2.m_pRight
= 0;
node3.m_pLeft
= 0;
node3.m_pRight
= 0;
ConvertNode(
&node1, 0);
cout
<<"node 2 = "<<node2.m_nValue<<endl;
cout
<<"node 2's next = "<<node2.m_pRight->m_nValue<<endl;
cout
<<"node 2's next's next = "<<node2.m_pRight->m_pRight->m_nValue;
return 1;
}

///////////////////////////////////////////////////////////////////////
// Covert a sub binary-search-tree into a sorted double-linked list
// Input: pNode - the head of the sub tree
// asRight - whether pNode is the right child of its parent
// Output: if asRight is true, return the least node in the sub-tree
// else return the greatest node in the sub-tree
///////////////////////////////////////////////////////////////////////
BSTreeNode* ConvertNode(BSTreeNode* pNode, bool asRight)
{
if(!pNode)
return NULL;

BSTreeNode
*pLeft = NULL;
BSTreeNode
*pRight = NULL;

// Convert the left sub-tree
if(pNode->m_pLeft)
pLeft
= ConvertNode(pNode->m_pLeft, false);

// Connect the greatest node in the left sub-tree to the current node
if(pLeft)
{
pLeft
->m_pRight = pNode;//左子树中的最大元素的右指针指向当前元素
pNode->m_pLeft = pLeft;//当前元素的左指针指向左子树中的最大元素
}

// Convert the right sub-tree
if(pNode->m_pRight)
pRight
= ConvertNode(pNode->m_pRight, true);

// Connect the least node in the right sub-tree to the current node
if(pRight)
{
pNode
->m_pRight = pRight;//同左子树中的连接操作
pRight->m_pLeft = pNode;//见上
}

BSTreeNode
*pTemp = pNode;

// If the current node is the right child of its parent,
// return the least node in the tree whose root is the current node
if(asRight)
{
while(pTemp->m_pLeft)
pTemp
= pTemp->m_pLeft;
}
// If the current node is the left child of its parent,
// return the greatest node in the tree whose root is the current node
else
{
while(pTemp->m_pRight)
pTemp
= pTemp->m_pRight;
}

return pTemp;
}

  

posted on 2011-07-21 11:29  kkmm  阅读(1693)  评论(0编辑  收藏  举报