C++實現二叉樹鏡像(翻轉)

來源:互聯網
上載者:User

標籤:二叉樹翻轉 二叉樹鏡像 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++實現二叉樹鏡像(翻轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.