还原二叉树
会还原吗?
先利用前序和中序序列建树,再利用二叉树遍历得到树的高度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| #include<iostream> using namespace std;
typedef struct BTNode { char c; BTNode* left; BTNode* right; }*BTree;
BTree CreateBT(char a[], char b[], int N) { if (N == 0) return NULL; BTree t = new BTNode; t->c = a[0]; int mid; for (mid = 0; mid < N; ++mid) { if (b[mid] == a[0]) break; } t->left = CreateBT(a+1,b,mid); t->right = CreateBT(a+mid+1,b+mid+1,N-mid-1); return t; }
void InOrder(BTree T) { if (T) { InOrder(T->left); cout << T->c; InOrder(T->right); } }
int BinaryTreeHeight(BTree T) { int BTreeHeight = 0; if (T) { int LeftHeight = BinaryTreeHeight(T->left); int RightHeight = BinaryTreeHeight(T->right); BTreeHeight = LeftHeight >= RightHeight ? LeftHeight + 1 : RightHeight + 1; } return BTreeHeight; }
int main() { int N; cin >> N; char* a = new char[N]; char* b = new char[N]; for (int i = 0; i < N; ++i) cin >> a[i]; for (int i = 0; i < N; ++i) cin >> b[i]; BTree T = CreateBT(a, b, N); cout << BinaryTreeHeight(T); return 0; }
|