分享

算法8(输入一颗二元查找树,将该树转换为它的镜像)

 白雪~~~ 2012-03-10

 

题目:

输入一颗二元查找树,将该树转换为它的镜像,即在转换后的二元查找树中,左子树的结点都大于右子树的结点。
用递归和循环两种方法完成树的镜像转换。
例如输入:
8
/ \
6 10
/\ /\
5 7 9 11
输出:
8
/ \
10 6
/\ /\
11 9 7 5
定义二元查找树的结点为:
struct BSTreeNode // a node in the binary search tree (BST)
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};

思路一:

这道题很容易就让人想到解决方案,镜像的实现在这里可以直接交换左右节点就可以实现,用递归实现比较简单,用循环来实现的话就稍微麻烦一点,要借用队列来实现.

代码如下:

  1. #include "stdafx.h"
  2. #include <assert.h>
  3. #include "Queue.h"
  4. /*--------------------------------
  5. 查找树转换为自己的镜像算法.
  6. Copyright by yuucyf. 2011.07.18
  7. ----------------------------------*/
  8. void AddBSTreeNode(S_BSTreeNode* &pRoot, int nValue)
  9. {
  10. if (NULL == pRoot)
  11. {
  12. pRoot = new S_BSTreeNode;
  13. assert(NULL != pRoot);
  14. pRoot->nValue = nValue;
  15. return;
  16. }
  17. if (pRoot->nValue > nValue)
  18. {
  19. AddBSTreeNode(pRoot->psLeft, nValue);
  20. }
  21. else if ( pRoot->nValue < nValue)
  22. {
  23. AddBSTreeNode(pRoot->psRight, nValue);
  24. }
  25. }
  26. void SwapLeftRightNode(S_BSTreeNode* psNode)
  27. {
  28. S_BSTreeNode *pTemp = psNode->psLeft;
  29. psNode->psLeft = psNode->psRight;
  30. psNode->psRight = pTemp;
  31. }
  32. //递归实现.
  33. void BuildImage_Recursion(S_BSTreeNode* psNode)
  34. {
  35. if (NULL == psNode)
  36. return;
  37. SwapLeftRightNode(psNode);
  38. BuildImage_Recursion(psNode->psLeft);
  39. BuildImage_Recursion(psNode->psRight);
  40. }
  41. //循环实现.(层次遍历,借用队列来实现)
  42. void BuildImage_Loop(S_BSTreeNode* psNode)
  43. {
  44. if (NULL == psNode)
  45. return;
  46. C_Queue<S_BSTreeNode *> queueNode;
  47. queueNode.QInsert(psNode);
  48. while (!queueNode.QEmpty())
  49. {
  50. psNode = queueNode.QDelete();
  51. SwapLeftRightNode(psNode);
  52. if (psNode->psLeft)
  53. queueNode.QInsert(psNode->psLeft);
  54. if (psNode->psRight)
  55. queueNode.QInsert(psNode->psRight);
  56. }
  57. }
  58. void PrintfAllNodeValue(const S_BSTreeNode* psNode)
  59. {
  60. if (NULL == psNode)
  61. return;
  62. _tprintf(_T("%d\n"), psNode->nValue);
  63. PrintfAllNodeValue(psNode->psLeft);
  64. PrintfAllNodeValue(psNode->psRight);
  65. }
  66. int _tmain(int argc, _TCHAR* argv[])
  67. {
  68. S_BSTreeNode *psRoot = NULL;
  69. AddBSTreeNode(psRoot, 8);
  70. AddBSTreeNode(psRoot, 6);
  71. AddBSTreeNode(psRoot, 10);
  72. AddBSTreeNode(psRoot, 5);
  73. AddBSTreeNode(psRoot, 7);
  74. AddBSTreeNode(psRoot, 9);
  75. AddBSTreeNode(psRoot, 11);
  76. PrintfAllNodeValue(psRoot);
  77. //BuildImage_Recursion(psRoot);
  78. BuildImage_Loop(psRoot);
  79. PrintfAllNodeValue(psRoot);
  80. return 0;
  81. }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多