7-4 交換二叉樹中每個結點的左孩子和右孩子 (20 分)


題目:

以二叉鏈表作為二叉樹的存儲結構,交換二叉樹中每個結點的左孩子和右孩子。

思路:

首先根據給出的字符串先把二叉樹建起來,這里稍稍卡了一下(所以決定寫個博客存一下);

建起來后就好說了,遞歸交換左右子樹;

然后遞歸中序遍歷就ok了!

代碼:

#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <iomanip>
#define MAX 1000000000
#define inf 0x3f3f3f3f
#define FRE() freopen("in.txt","r",stdin)

using namespace std;
typedef long long ll;
const int maxn = 10005;
struct Node
{
    char date;
    Node* rt;
    Node* lt;
};
typedef Node* Tree;
int len,idx;
string str;

void build(Tree& root)
{
    if(str[idx]=='#'||idx==len) return;
    root = new Node;
    root->date = str[idx];
    root->lt = NULL;
    root->rt = NULL;
    idx++;//因為在字符串中是一直向后走的,所以這里用一個全局變量表示字符串你的下標就ok了
    build(root->lt);
    idx++;
    build(root->rt);
    return;
}

void exchangeNode(Tree& root)//從根節點一次交換左右子樹就搞定!
{
    if(root->lt==NULL && root->rt==NULL)
        return;
    Node* temp;
    temp = root->lt;
    root->lt = root->rt;
    root->rt = temp;
    if(root->lt!=NULL)
        exchangeNode(root->lt);
    if(root->rt!=NULL)
        exchangeNode(root->rt);
}

void midTravel(Tree root)//中序遍歷二叉樹
{
    if(root->lt!=NULL)
        midTravel(root->lt);
    printf("%c",root->date);
    if(root->rt!=NULL)
        midTravel(root->rt);
}

int main()
{
   // FRE();
    cin>>str;
    len = str.length();
    idx = 0;
    Tree root = NULL;
    build(root);
    midTravel(root);
    printf("\n");
    exchangeNode(root);
    midTravel(root);
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM