第15題:
題目:輸入一顆二元查找樹,將該樹轉換為它的鏡像,
即在轉換後的二元查找樹中,左子樹的結點都大於右子樹的結點。
用遞歸和循環兩種方法完成樹的鏡像轉換。
例如輸入:
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
};
[cpp] #include<iostream>
#include<iomanip>
#include<stack>
using namespace std;
//定義二元查找樹的結點為:
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
};
void cfun(BSTreeNode *pt)
{
if(!pt){
return;
}
BSTreeNode * ptem=pt->m_pLeft;
pt->m_pLeft=pt->m_pRight;
pt->m_pRight=ptem;
if(pt->m_pLeft){
cfun(pt->m_pLeft);
}
if(pt->m_pRight){
cfun(pt->m_pRight);
}
}
//考慮用循環實現這個算法
void MirrorIteratively(BSTreeNode *pTreeHead)
{
if(!pTreeHead)
return;
std::stack<BSTreeNode *> stackTreeNode;
stackTreeNode.push(pTreeHead);
while(stackTreeNode.size())
{
BSTreeNode *pNode = stackTreeNode.top();
stackTreeNode.pop();
// swap the right and left child sub-tree
BSTreeNode *pTemp = pNode->m_pLeft;
pNode->m_pLeft = pNode->m_pRight;
pNode->m_pRight = pTemp;
// push left child sub-tree into stack if not null
if(pNode->m_pLeft)
stackTreeNode.push(pNode->m_pLeft);
// push right child sub-tree into stack if not null
if(pNode->m_pRight)
stackTreeNode.push(pNode->m_pRight);
}
}
//這個題目展示了遞歸變成循環的方法
int main()
{
system("pause");
return 0;
}
#include<iostream>
#include<iomanip>
#include<stack>
using namespace std;
//定義二元查找樹的結點為:
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
};
void cfun(BSTreeNode *pt)
{
if(!pt){
return;
}
BSTreeNode * ptem=pt->m_pLeft;
pt->m_pLeft=pt->m_pRight;
pt->m_pRight=ptem;
if(pt->m_pLeft){
cfun(pt->m_pLeft);
}
if(pt->m_pRight){
cfun(pt->m_pRight);
}
}
//考慮用循環實現這個算法
void MirrorIteratively(BSTreeNode *pTreeHead)
{
if(!pTreeHead)
return;
std::stack<BSTreeNode *> stackTreeNode;
stackTreeNode.push(pTreeHead);
while(stackTreeNode.size())
{
BSTreeNode *pNode = stackTreeNode.top();
stackTreeNode.pop();
// swap the right and left child sub-tree
BSTreeNode *pTemp = pNode->m_pLeft;
pNode->m_pLeft = pNode->m_pRight;
pNode->m_pRight = pTemp;
// push left child sub-tree into stack if not null
if(pNode->m_pLeft)
stackTreeNode.push(pNode->m_pLeft);
// push right child sub-tree into stack if not null
if(pNode->m_pRight)
stackTreeNode.push(pNode->m_pRight);
}
}
//這個題目展示了遞歸變成循環的方法
int main()
{
system("pause");
return 0;
}