演算法習題15:二叉樹映象(翻轉)
阿新 • • 發佈:2019-02-01
題目:輸入一顆二元查詢樹,將該樹轉換為它的映象,
即在轉換後的二元查詢樹中,左子樹的結點都大於右子樹的結點。
用遞迴和迴圈兩種方法完成樹的映象轉換。
例如輸入:
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
};
----------------------------------
今天這兩道題相對來說還是比較簡單,怪不得連答案都沒咯
映象,就是交換左右子樹,正如我前面題目裡遇到的一樣,二叉樹這種問題最便捷的就是迴歸到遞迴遍歷問題上,這樣解題就思路開闊了
//============================================================================ // Name : RevertBT.cpp // Author : YLF // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> 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 addNode(BSTreeNode* &p, int value); void printLDR(BSTreeNode* p); void Mirror(BSTreeNode* p); int main() { BSTreeNode *head = NULL; int input = 0; while(true){ cin>>input; if(input != -1) addNode(head, input); else break; } printLDR(head); cout<<endl; Mirror(head); printLDR(head); return 0; } void addNode(BSTreeNode* &p, int value){ if(p == NULL){ BSTreeNode* temp = new BSTreeNode(); temp->m_nValue = value; temp->m_pLeft = NULL; temp->m_pRight = NULL; p = temp; }else{ if(value < p->m_nValue) addNode(p->m_pLeft, value); else{ addNode(p->m_pRight, value); } } } /* * 翻轉映象 */ void Mirror(BSTreeNode* p){ if(p == NULL) return; //先映象 BSTreeNode* temp = p->m_pLeft; p->m_pLeft = p->m_pRight; p->m_pRight = temp; //再遍歷 Mirror(p->m_pLeft); Mirror(p->m_pRight); } /* * 中序遍歷 */ void printLDR(BSTreeNode* p){ if(p == NULL) return; printLDR(p->m_pLeft); cout<<p->m_nValue<<" "; printLDR(p->m_pRight); }