#include <iostream>
#include <queue>
#include <stack>
using namespace std;
typedef struct BTreeNode* BTree;
struct BTreeNode {
int data;
BTree lch;
BTree rch;
};
BTree createBTree() {
BTree root = NULL;
int data;
cin >> data;
if(data!=-1){
root = new BTreeNode;
root->data = data;
root->lch = createBTree();
root->rch = createBTree();
}
return root;
}
BTree CXcreateBTree() {
queue<BTree> Q;
int data;
BTree root,temp;
cin >> data;
if (data != -1) {
root = new BTreeNode;
root->data = data;
root->lch = NULL;
root->rch = NULL;
Q.push(root);
}
else {
return NULL;
}
while (!Q.empty()) {
temp = Q.front();
Q.pop();
cin >> data;
if (data != -1) {
temp->lch = new BTreeNode;
temp->lch->data = data;
Q.push(temp->lch);
}
else {
temp->lch = NULL;
}
cin >> data;
if (data != -1) {
temp->rch = new BTreeNode;
temp->rch->data = data;
Q.push(temp->rch);
}
else {
temp->rch = NULL;
}
}
return root;
}
void inBTree(BTree root) {
if (root!= NULL) {
inBTree(root->lch);
cout << root->data << ' ';
inBTree(root->rch);
}
}
void prevBTree(BTree root) {
if (root!=NULL) {
cout << root->data << ' ';
prevBTree(root->lch);
prevBTree(root->rch);
}
}
void lastBTree(BTree root) {
if (root != NULL) {
lastBTree(root->lch);
lastBTree(root->rch);
cout << root->data << ' ';
}
}
void breadthBTree(BTree root) {
queue<BTree> Q;
if (root != NULL) {
Q.push(root);
}
while (!Q.empty()) {
cout << Q.front()->data << ' ';
if (Q.front()->lch) Q.push(Q.front()->lch);
if (Q.front()->rch) Q.push(Q.front()->rch);
Q.pop();
}
}
bool findO(BTree root, int a,vector<BTree> &aa) {
if (root == NULL) return false;
if (root->data != a) {
if (findO(root->lch, a, aa)) {
aa.push_back(root); return true;
}
if (findO(root->rch, a, aa)) {
aa.push_back(root); return true;
}
return false;
}
else {
aa.push_back(root);
return true;
}
}
BTree findP(BTree root,int a,int b) {
vector<BTree> aa;
vector<BTree> bb;
bool findA = findO(root, a, aa);
bool findB = findO(root, b, bb);
BTree temp = NULL;
if (findA == true && findB == true) {
int minsize = aa.size() > bb.size() ? bb.size() : aa.size();
int i = aa.size() - minsize;
int j = bb.size() - minsize;
for (; i < aa.size(), j < bb.size(); ++i, ++j) {
if (aa[i] == bb[j]) {
temp = aa[i];
break;
}
}
}
return temp;
}
void deepBTree(BTree root) {
stack<BTree> S;
S.push(root);
while (!S.empty()) {
BTree temp = S.top();
cout << temp->data << ' ';
S.pop();
if (temp->rch) {
S.push(temp->rch);
}
if (temp->lch) {
S.push(temp->lch);
}
}
cout << endl;
}
int main() {
BTree root = CXcreateBTree();
cout << "前序遍历:";
prevBTree(root);
cout<< endl;
cout << "中序遍历:";
inBTree(root);
cout << endl;
cout << "后序遍历:";
lastBTree(root);
cout << endl;
cout << "广度遍历:";
breadthBTree(root);
cout << endl;
cout << "深度遍历:";
deepBTree(root);
cout << endl;
int a, b;
cin >> a >> b;
BTree res=findP(root, a, b);
cout << res->data << endl;
}
二叉树前序创建、层序创建、前(中、后、深度、广度)序遍历,寻找祖先节点
最新推荐文章于 2021-11-02 09:52:18 发布