C语言 二叉查找树镜像

来源:互联网 发布:linux kernel usleep 编辑:程序博客网 时间:2024/06/01 10:41
题目:输入一颗二元查找树,将该树转换为它的镜像,即在转换后的二元查找树中,左子树的结点都大于右子树的结点。用递归和循环两种方法完成树的镜像转换。

例如输入:

     8
    /  \
  6      10
 /\       /\
5  7    9   11

输出:

      8
    /  \
  10    6
 /\      /\
11  9  7  5

typedef struct BSTreenode{int data;struct BSTreenode *pLeft;struct BSTreenode *pRight;}BST;void mirrorBST(BST *pRoot){if(pRoot == NULL){return ;}BST *tempNode = pRoot->pLeft;pRoot->pLeft = pRoot->pRight;pRoot->pRight = tempNode;if(pRoot->pLeft){mirrorBST(pRoot->pLeft);}if(pRoot->pRight){mirrorBST(pRoot->pRight);}}void mirrorBST01(BST *pRoot){if(pRoot == NULL){return;}deque<BST *>BSTNode;BSTNode.push_back(pRoot);while(!BSTNode.empty()){BST *pNode = BSTNode.front();BSTNode.pop_front();BST *tempNode = pNode->pLeft;pNode->pLeft = pNode->pRight;pNode->pRight = tempNode;if(pNode->pLeft){BSTNode.push_back(pNode->pLeft);}if(pNode->pRight){BSTNode.push_back(pNode->pRight);}}}


0 0
原创粉丝点击