5.1.7—二叉树的遍历—Recover Binary Sear Tree

来源:互联网 发布:浪潮软件重大新闻 编辑:程序博客网 时间:2024/06/06 11:43
描述
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note: A solution using O(n) space is prey straight forward. Could you devise a constant space

solution?

#ifndef BINTREE_H_#define BINTREE_H_#include<vector>#include<iostream>struct BinTree{int value;BinTree *left;BinTree *right;};BinTree *CreateNode(int data);void Connect(BinTree *pRoot, BinTree *pLeft, BinTree *pRight);void PrintOneNode(BinTree *pRoot);void PrintTree(BinTree *pRoot);void DestroyTree(BinTree *pRoot);#endif
#include"BinTree.h"using namespace std;BinTree *CreateNode(int data){BinTree *pRoot = new BinTree();pRoot->value = data;pRoot->left = pRoot->right = NULL;return pRoot;}void Connect(BinTree *pRoot, BinTree *pLeft, BinTree *pRight){pRoot->left = pLeft;pRoot->right = pRight;}void PrintOneNode(BinTree *pRoot){if (pRoot){cout << pRoot->value << endl;if (pRoot->left)cout << pRoot->value << ":left node is:" << pRoot->left->value << endl;else cout << pRoot->value << ":left node is null" << endl;if (pRoot->right)cout << pRoot->value << ":right node is:" << pRoot->right->value << endl;cout << pRoot->value << ":right node is null" << endl;}else{cout << "the node is NULL!" << endl;}}void PrintTree(BinTree *pRoot){PrintOneNode(pRoot);if (pRoot->left)PrintTree(pRoot->left);if (pRoot->right)PrintTree(pRoot->right);}void DestroyTree(BinTree *pRoot){if (!pRoot)return;else{BinTree *pLeft = pRoot->left;BinTree *pRight = pRoot->right;delete pRoot;DestroyTree(pLeft);DestroyTree(pRight);}}




#include"BinTree.h"#include<iostream>#include<vector>#include<stack>using namespace std;void CoverBST(BinTree *pRoot){if (!pRoot)return;stack<BinTree *>tmp;vector<BinTree *> res;BinTree *p=pRoot;while (!tmp.empty()||p){while (p){tmp.push(p);p = p->left;}if (!tmp.empty()){BinTree *q = tmp.top();tmp.pop();res.push_back(q);p = q->right;}}//===int index2 = 0, index1 = 0;for (int i = 0; i < res.size()-1; i++){if (res[i]->value > res[i + 1]->value){index1 = i;break;}}for (int i = res.size() - 1; i > 0; i--){if (res[i - 1]->value > res[i]->value){index2 = i;break;}}int value = res[index1]->value;res[index1]->value = res[index2]->value;res[index2]->value = value;}int main(){BinTree *p6 = CreateNode(6);BinTree *p4 = CreateNode(4);BinTree *p1 = CreateNode(1);BinTree *p7 = CreateNode(7);BinTree *p8 = CreateNode(8);BinTree *p5 = CreateNode(5); BinTree *p10 = CreateNode(10);Connect(p6, p4, p8);Connect(p4, p1, p7);Connect(p8, p5, p10);cout << "Before:"<<endl; PrintTree(p6);CoverBST(p6);cout << "After:"<<endl; PrintTree(p6);DestroyTree(p6);}




阅读全文
0 0
原创粉丝点击