標籤:二叉樹翻轉 二叉樹鏡像 c++ 二叉樹
描述:
給定一個二叉樹的根,將二叉樹翻轉
解決方案:
前序走訪二叉樹,交換左右子節點
程式碼範例:
#include <iostream>#include <cstdio>using namespace std;class Node{ private: Node* left; Node* right; int value; public: int Data(){ return value; } Node* Left(){ return left; } Node* Right(){ return right; } Node(int _value):value(_value){ left = NULL; right = NULL; } void SetLeft(Node* _left){ left = _left; } void SetRight(Node* _right){ right = _right; }};class Tree{ public: Node* root;};//建立一顆二叉樹Node* Construct(){ Node* n1 = new Node(1); Node* n2 = new Node(2); Node* n3 = new Node(3); Node* n4 = new Node(4); Node* n5 = new Node(5); n1->SetLeft(n2); n1->SetRight(n3); n3->SetLeft(n4); n3->SetRight(n5); return n1;}//前序遞迴遍曆void PreOrder(Node* root){ if(NULL == root){ cout << endl; return; } cout << root->Data() << " "; if(NULL != root->Left()){ PreOrder(root->Left()); } if(NULL != root->Right()){ PreOrder(root->Right()); }}//翻轉void Image(Node* root){ if(NULL == root){ return; } if(NULL == root->Left() && NULL == root->Right()){ return; } /* 交換左右子樹 */ Node* temp = root->Left(); root->SetLeft(root->Right()); root->SetRight(temp); if(NULL != root->Left()){ Image(root->Left()); } if(NULL != root->Right()){ Image(root->Right()); }}int main(void){ Node* root = Construct(); cout << endl; PreOrder(root); Image(root); cout << endl; PreOrder(root); return 1;}
本文出自 “迷途知返的程式猿” 部落格,請務必保留此出處http://lth2015.blog.51cto.com/10613847/1683948
C++實現二叉樹鏡像(翻轉)