C++实现二叉树镜像(翻转)

描述:

        给定一个二叉树的根,将二叉树翻转

解决方案:

        前序遍历二叉树,交换左右子节点

代码示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

#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;

}

猜你喜欢

转载自blog.csdn.net/beyond_2016/article/details/81220887