描述:
给定一个二叉树的根,将二叉树翻转
解决方案:
前序遍历二叉树,交换左右子节点
代码示例:
#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
原文地址:http://lth2015.blog.51cto.com/10613847/1683948