1. 程式人生 > >7-4 交換二叉樹中每個結點的左孩子和右孩子 (20 分)

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

freopen names bit include cin using nbsp int date

題目:

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

思路:

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

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

然後遞歸中序遍歷就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; }

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