题目描述
按中序遍历和后序遍历给出一棵二叉树,求这棵二叉树中叶子节点权值的最小值。
输入保证叶子节点的权值各不相同。
输入
第一行输入一个整数t,表示有t组测试数据。
对于每组测试数据,首先输入一个整数N (1 <= N <=10000),代表二叉树有N个节点,接下来的一行输入这棵二叉树中序遍历的结果,最后一行输入这棵二叉树后序遍历的结果。
输出
对于每组测试数据,输出一个整数,代表二叉树中叶子节点权值最小值。
样例输入
3
7
3 2 1 4 5 7 6
3 1 2 5 6 7 4
8
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
1
255
255样例输出
1
3
255
#include <iostream>
#include <algorithm>
using namespace std;
int *m;
int *h;
int len;
int ans;
class Binary_tree_node
{
public:
int data; //数据域
Binary_tree_node *LeftChild; //左孩子
Binary_tree_node *RightChild; //右孩子
Binary_tree_node() : LeftChild(NULL), RightChild(NULL){};
~Binary_tree_node(){};
};
class Binary_tree
{
private:
Binary_tree_node *root;
Binary_tree_node *createBiTree(int *In, int *Post, int n)
{
if (n == 0)
{
return NULL;
}
Binary_tree_node *T = new Binary_tree_node();
int i;
T->data = Post[n - 1];
for (i = 0; In[i] != Post[n - 1]; i++);
T->LeftChild = createBiTree(In, Post, i);
T->RightChild = createBiTree(In + i + 1, Post + i, n - i - 1);
return T;
}
void min_weight(Binary_tree_node *t)
{
if (t)
{
if (!t->LeftChild && !t->RightChild)
{
ans = min(ans, t->data);
}
min_weight(t->LeftChild);
min_weight(t->RightChild);
}
}
public:
Binary_tree(){};
~Binary_tree(){};
void createTree()
{
root = createBiTree(m, h, len);
}
void min_weight()
{
min_weight(root);
}
};
int main()
{
int t;
cin >> t;
while (t--)
{
ans = 99999999;
cin >> len;
m = new int[len];
h = new int[len];
for (int i = 0; i < len; i++)
{
cin >> m[i];
}
for (int i = 0; i < len; i++)
{
cin >> h[i];
}
Binary_tree *bt = new Binary_tree();
bt->createTree();
bt->min_weight();
cout << ans << endl;
}
return 0;
}