恢复被交换二叉搜索树的节点值

来源:互联网 发布:python 扑克 编辑:程序博客网 时间:2024/06/08 13:10
#include <iostream>#include <vector>#include<algorithm>using namespace std;vector<int> G;//数据类class Data {public:int m, n;Data(int m, int n) {this->m = m;this->n = n;}};struct BTNode{int m_value;BTNode *m_left;BTNode *m_right;};//先序创建二叉树void CreatBTree(BTNode *&root){int nValue;cin >> nValue;if (0 == nValue){return;}else{root = new BTNode();root->m_value = nValue;CreatBTree(root->m_left);CreatBTree(root->m_right);}}void Search1(BTNode *pRoot)//将数字压到G中{if (pRoot != NULL) {Search1(pRoot->m_left);G.push_back(pRoot->m_value);Search1(pRoot->m_right);}}Data *Search() {int length = G.size();int m, n;for (int i = 0; i < length; i++) {if (i == 0 && G[i] > G[i + 1]) {m = i;}else {if (i != 0 && i < length - 1 && (G[i - 1]<G[i] && G[i]>G[i + 1])) {m = i;}else {if (i != 0 && i < length - 1 && (G[i - 1] > G[i] && G[i] < G[i + 1])) {n = i;}else {if (i == length - 1 && G[i] < G[i - 1]) {n = i;}}}}}return new Data(m, n);}void InOrder(BTNode *&pRoot, Data *data) {if (pRoot != NULL) {InOrder(pRoot->m_left, data);if (pRoot->m_value == G[data->m]) {pRoot->m_value = G[data->n];}else {if (pRoot->m_value == G[data->n]) {pRoot->m_value = G[data->m];}}InOrder(pRoot->m_right, data);}}void InOrder1(BTNode *&pRoot, Data *data) {if (pRoot != NULL) {InOrder(pRoot, data);cout << pRoot->m_value << " ";InOrder(pRoot, data);}}void Print(BTNode *&pRoot) {if (pRoot != NULL) {Print(pRoot->m_left);cout << pRoot->m_value << " ";Print(pRoot->m_right);}}int main(){BTNode *pRoot = NULL;CreatBTree(pRoot);Search1(pRoot);Data *data = Search();//InOrder1(pRoot,data);InOrder(pRoot, data);Print(pRoot);//Print1();system("pause");return 0;}

1 0
原创粉丝点击